JSP教程(八)—— Servlet实现验证码


1  实现步骤

1.1  验证码基本概念

验证码包含两部分:

  • 输入框
  • 显示验证码的图片

网页显示验证码:

1 <input type="text id="verifyCode" name="verifyCode" size="6"/>
1 <img alt="验证码" id="safecode" src="<%=request.getComtextPath()%>/servlet/ImageServlet">

1.2  生成图片

生成图片用到的类

  • BufferedImage图像数据缓冲区
  • Graphice绘制图片
  • Color获取颜色
  • Random生成随机数
  • ImageIO输出图片

1.3  生成图片的实现类

ImageServlet类

  1. 定义BufferedImage对象
  2. 获得Graphice对象
  3. 通过Random产生随机验证码信息
  4. 使用Graphice绘制图片
  5. 记录验证码信息到session中
  6. 使用ImageIO输出图片

1.4  校验验证码是否正确

LoginServlet类

  1. 获取页面验证码
  2. 获取session保存的验证码
  3. 比较验证码
  4. 返回校验结果

2  代码实现

注意:需要将相关jar包导入项目

主页面代码(index.jsp)

1 <script type="text/javascript">
2     function reloadCode(){
3         var time = new Date().getTime();
4         document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImageServlet?d="+time;
5     }
6 </script>
1 <body>
2     <form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="get">
3         验证码:<input type="text" name="checkcode"/>
4         <img alt="验证码" id="imagecode" src="<%=request.getContextPath() %>/servlet/ImageServlet"/>
5         <a href="javascript: reloadCode();">看不清楚</a><br>
6         <input type="submit" value="提交">
7     </form>
8 </body>

生成图片的Java代码

 1 package com.muke;
 2 
 3 import java.awt.Color;
 4 import java.awt.Graphics;
 5 import java.awt.image.BufferedImage;
 6 import java.io.IOException;
 7 import java.util.Random;
 8 import javax.imageio.ImageIO;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 public class ImageServlet extends HttpServlet {
14 
15     /**
16      * 
17      */
18     private static final long serialVersionUID = 1L;
19 
20     public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
21         BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);//长度,宽度,图片类型
22         Graphics g = bi.getGraphics();//画一个图片
23         Color c = new Color(200,150,255);//定义背景颜色
24         g.setColor(c);
25         g.fillRect(0, 0, 68, 22);//背景框(坐标)
26         
27         char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//把字母和数字全部列出来
28         Random r = new Random();//随机数类
29         int len=ch.length,index;//获取数组长度和index随机数
30         StringBuffer sb = new StringBuffer();//保存随机字符的一个类
31         for(int i=0; i<4; i++){//取四位随机数
32             index = r.nextInt(len);//获取一个随机数(数组长度范围之内)
33             g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));//随机获得一个颜色
34             g.drawString(ch[index]+"", (i*15)+3, 18);//把字符画到图片上//字符  x坐标  y坐标
35             sb.append(ch[index]);//保存随机字符
36         }
37         request.getSession().setAttribute("piccode", sb.toString());
38         ImageIO.write(bi, "JPG", response.getOutputStream());//输出//对象  类型  输出位置
39     }
40 }

验证输入的Java代码

 1 package com.muke;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 public class LoginServlet extends HttpServlet{
10 
11     /**
12      * 
13      */
14     private static final long serialVersionUID = 1L;
15 
16     public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
17         
18         String piccode = (String) request.getSession().getAttribute("piccode");
19         String checkcode = request.getParameter("checkcode");
20         checkcode = checkcode.toUpperCase();
21         response.setContentType("text/html;charset=gbk");
22         PrintWriter out = response.getWriter();
23         if(checkcode.equals(piccode)){
24             out.println("验证码输入正确!");
25         }else{
26             out.println("验证码输入错误!!!");
27         }
28         out.flush();
29         out.close();
30     }
31 }

配置文件(web.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.4" 
 3     xmlns="http://java.sun.com/xml/ns/j2ee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 6     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 7     
 8     <servlet>
 9         <servlet-name>ImageServlet</servlet-name>
10         <servlet-class>com.muke.ImageServlet</servlet-class>
11     </servlet>
12     <servlet>
13         <servlet-name>LoginServlet</servlet-name>
14         <servlet-class>com.muke.LoginServlet</servlet-class>
15     </servlet>
16     <servlet-mapping>
17         <servlet-name>ImageServlet</servlet-name>
18         <url-pattern>/servlet/ImageServlet</url-pattern>
19     </servlet-mapping>
20     <servlet-mapping>
21         <servlet-name>LoginServlet</servlet-name>
22         <url-pattern>/servlet/LoginServlet</url-pattern>
23     </servlet-mapping>
24     
25     <welcome-file-list>
26         <welcome-file>index.jsp</welcome-file>
27     </welcome-file-list>
28 </web-app>

完整代码在https://pan.baidu.com/s/1kW8w4tD。

3  结果输出

posted @ 2018-02-19 15:34  祁俊辉  阅读(504)  评论(0编辑  收藏  举报