一、实验目的 掌握怎样在JSP中使用javabean |
二、实验项目内容(实验题目) 编写代码,掌握servlet的用法。【参考课本 上机实验1 】 |
三、源代码以及执行结果截图: 源代碼: inputVertex.jsp: <%@ page language="java" contentType="text/html; uft-8" pageEncoding="utf-8"%> <style> #tom{ font-family:宋体;font-size:26;color:blue } </style> <% String s ="(20,220)(220,20)(420,220)(220,420)"; %> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body bgcolor=#ffccff> <p id=tom> <form action="drawPolygon" id= tom method=post> 输入多边形的顶点,格式是(m,n)<br>m,n为整数 0<=m<=800,0<=n<=600<br> <textArea name="polygonVertex" id =tom rows=5 cols=30 > <%= s %> </textArea> <br><input type=submit id=tom value="提交"/> </form> </p> </body> </html> web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>drawPolygon</servlet-name> <servlet-class>moon.sun.DrawPolygon_Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>drawPolygon</servlet-name> <url-pattern>/drawPolygon</url-pattern> </servlet-mapping> </web-app> DrawPolygon_Servlet: package moon.sun; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.awt.image.BufferedImage; import java.awt.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.awt.geom.*; import javax.imageio.ImageIO; public class DrawPolygon_Servlet extends HttpServlet{ HttpServletRequest request; HttpServletResponse response; public void init(ServletConfig config) throws ServletException{ super.init(config); } public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{ request.setCharacterEncoding("utf-8"); String polygonVertex = request.getParameter("polygonVertex"); if(polygonVertex == null||polygonVertex.length()==0){ response.sendRedirect("ch6_1.jsp"); return; } response.setContentType("image/jpeg"); Polygon polygon = getPolygon(polygonVertex); BufferedImage image = getImage(polygon); OutputStream outClient= response.getOutputStream(); boolean boo =ImageIO.write(image,"jpeg",outClient); } Polygon getPolygon(String polygonVertex){ Polygon polygon = new Polygon(); Pattern pattern; Matcher matcher; String regex="(\\d+[,, ]+\\d+)" ; pattern = Pattern.compile(regex); matcher = pattern.matcher(polygonVertex); while(matcher.find()) { String str = matcher.group(); String []vertex = str.split("[( ),, ]+"); polygon.addPoint(Integer.parseInt(vertex[0]),Integer.parseInt(vertex[1])); } return polygon; } BufferedImage getImage(Shape shape){ int width=1000, height=800; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.fillRect(0, 0, width, height); Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(Color.blue); g_2d.draw(shape); return image; } } |
代碼結果圖: |