700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 利用Servlet生成动态验证码

利用Servlet生成动态验证码

时间:2023-03-14 07:55:50

相关推荐

利用Servlet生成动态验证码

在Servlet中,设置响应正文的类型为image/jpeg,表示响应的是一个图片,然后通过java.awt包中的操作图形图像的类来生成一个图像

java.awt.image.BufferedImage:创建该对象时,会在缓存中构造一个图像

java.awt.Graphics:该类的对象表示一个画笔,用来话矩形,写字,添加颜色

java.util.Random:该类的对象用于生成随机输

新建ValidateCodeServlet类

public class ValidateCodeServlet extends HttpServlet {

/*** Constructor of the object.*/public ValidateCodeServlet() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public Color getRandomColor(int fc,int bc){Random random = new Random();Color randomColor = null;if(fc>255) fc=255;if(bc>255) bc=255;//设置个0-255之间的随机颜色值int r=fc+random.nextInt(bc-fc);int g=fc+random.nextInt(bc-fc);int b=fc+random.nextInt(bc-fc);randomColor = new Color(r,g,b);return randomColor;//返回具有指定红色、绿色和蓝色值的不透明的 sRGB 颜色}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//禁止页面缓存response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "No-cache");response.setDateHeader("Expires", 0);response.setContentType("image/jpeg");//设置响应正文的MIME类型为图片int width=60, height=20; /**创建一个位于缓存中的图像,宽度60,高度20 */ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics();//获取用于处理图形上下文的对象,相当于画笔Random random = new Random(); //创建生成随机数的对象g.setColor(getRandomColor(200,250)); //设置图像的背景色g.fillRect(0, 0, width, height); //画一个矩形,坐标(0,0),宽度60,高度20 g.setFont(new Font("Times New Roman",Font.PLAIN,18)); //设定字体格式g.setColor(getRandomColor(160,200));for(int i=0;i<130;i++){ //产生130条随机干扰线int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl);//在图象的坐标(x,y)和坐标(x+x1,y+y1)之间画干扰线 } String strCode=""; for (int i=0;i<4;i++){ String strNumber=String.valueOf(random.nextInt(10)); //把随机数转换成String字符串strCode=strCode+strNumber;//设置字体的颜色g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));g.drawString(strNumber,13*i+6,16); //将验证码依次画到图像上,坐标(x=13*i+6,y=16)}request.getSession().setAttribute("Code",strCode); //把验证码保存到Session中 g.dispose(); //释放此图像的上下文以及它使用的所有系统资源ImageIO.write(image, "JPEG", response.getOutputStream()); //输出JPEG格式的图像 response.getOutputStream().flush(); //刷新输出流 response.getOutputStream().close();//关闭输出流 }/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here}

}

index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>用户注册</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">table{font-size:12px;font-family: 隶书;color:gray;border: 1px green solid;}input{font-size:12px;font-family: 隶书;color:gray;}</style></head><body><form action="" method="post"><table align="center"><tr><td>用户名:</td><td><input type="text" name="name" /></td></tr><tr><td>密码:</td><td><input type="password" name="pwd" /></td></tr><tr><td>性别:</td><td><input type="radio" name="sex" value="男" />男<input type="radio" name="sex" value="女" />女</td></tr><tr><td>年龄:</td><td><input type="text" name="age" /></td></tr><tr><td>Email:</td><td><input type="text" name="email" /></td></tr><tr><td>验证码:</td><td><img alt="" src="validatecode" ></td></tr><tr><td>输入验证码:</td><td><input type="text" name="code"/></td></tr><tr><td colspan="2" align="center"><input type="submit" value="注 册" /><input type="reset" value="重 置" /></td></tr></table></form></body></html>

web.xml文件配置

<servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>ValidateCodeServlet</servlet-name><servlet-class>com.lh.servlet.ValidateCodeServlet</servlet-class></servlet><servlet-mapping><servlet-name>ValidateCodeServlet</servlet-name><url-pattern>/validatecode</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。