javaweb之验证码验证技术

Posted java小斌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaweb之验证码验证技术相关的知识,希望对你有一定的参考价值。

今天学习了一个验证码校验技术,所以就写下了一些笔记,方便日后查看。首先创建web工程

1、然后在src目录下创建一个Servlet类,此类用来显示登录页面和错误信息提示

 1 package com.LHB;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /**
13  * Servlet implementation class Login
14  */
15 @WebServlet("/Login")
16 public class Login extends HttpServlet {
17     private static final long serialVersionUID = 1L;
18        
19     /**
20      * @see HttpServlet#HttpServlet()
21      */
22     public Login() {
23         super();
24         // TODO Auto-generated constructor stub
25     }
26 
27     /**
28      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
29      */
30     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31         
32         response.setContentType("text/html;charset=utf-8");
33         PrintWriter out = response.getWriter();
34         
35         //返回一个界面
36         
37         out.println("<h1>用户登录</h1>");
38         out.println("<form action=\'/CheckCode/LoginCl\' method=\'get\'>");
39         out.println("用户名:<input type=\'text\' name=\'id\'><br>");
40         out.println("密码:<input type=\'password\' name=\'password\'><br>");
41         out.println("验证码:<input type=\'text\' name=\'checkcode\'><img src=\'/CheckCode/CreateCode\'><br>");//加载验证码图片是只要将产生验证码的对应类路径指定到img标签中即可
42         out.println("<input type=\'submit\' value=\'登录\'><br>");
43         
44         out.println("</form>");
45         String err=(String) request.getAttribute("err");
46         if(err!=null) {
47             out.println(err);
48         }
49     }
50 
51     /**
52      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
53      */
54     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
55         // TODO Auto-generated method stub
56         doGet(request, response);
57     }
58 
59 }

2、继续创建一个Servlet,用来显示校验成功后的页面。

 1 package com.LHB;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /**
13  * Servlet implementation class LoginCl
14  */
15 @WebServlet("/LoginCl")
16 public class LoginCl extends HttpServlet {
17     private static final long serialVersionUID = 1L;
18        
19     /**
20      * @see HttpServlet#HttpServlet()
21      */
22     public LoginCl() {
23         super();
24         // TODO Auto-generated constructor stub
25     }
26 
27     /**
28      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
29      */
30     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31         
32         response.setContentType("text/html;charset=utf-8");
33         PrintWriter out = response.getWriter();
34         
35         //获取用户的id/password/输入验证码
36         String id = request.getParameter("id");
37         String passwd = request.getParameter("password");
38         String checkCode = request.getParameter("checkcode");
39         //取出session中验证码
40         String checkcode2 = (String) request.getSession().getAttribute("checkcode");
41                 
42         //1.先验证码
43         if(checkCode.equals(checkcode2)) {
44             //验证码ok
45             request.getRequestDispatcher("/OK").forward(request, response);
46             //到数据库去验证
47         }else {
48             request.setAttribute("err", "验证码错误");
49             request.getRequestDispatcher("/Login").forward(request, response);
50         }
51         
52         
53     }
54 
55     /**
56      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
57      */
58     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
59         // TODO Auto-generated method stub
60         doGet(request, response);
61     }
62 
63 }

3、最后创建验证码产生的Servlet,用来产生随机数校验码图片,并将该验证码图片返回到客户端。此类比较关键。

 1 package com.LHB;
 2 
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.Graphics;
 6 import java.awt.image.BufferedImage;
 7 import java.io.IOException;
 8 import java.util.Random;
 9 
10 import javax.imageio.ImageIO;
11 import javax.servlet.ServletException;
12 import javax.servlet.annotation.WebServlet;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 
18 /**
19  * Servlet implementation class CreateCode
20  */
21 @WebServlet("/CreateCode")
22 public class CreateCode extends HttpServlet {
23     private static final long serialVersionUID = 1L;
24        
25     /**
26      * @see HttpServlet#HttpServlet()
27      */
28     public CreateCode() {
29         super();
30         // TODO Auto-generated constructor stub
31     }
32 
33     /**
34      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
35      */
36     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
37         
38         //禁止浏览器缓冲随机图片
39         response.setDateHeader("Expires", -1);//防止启动浏览器时取先前缓冲的数据
40         response.setHeader("Cache-Control", "no-cache");
41         response.setHeader("Pragma", "no-cache");
42         
43         //通知客户机以图片方式打开发送过去的数据
44         response.setHeader("Content-Type", "image/jpeg");
45         
46         //在内存中创建一副图片
47         BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_BGR);
48         
49         //想图片上写数据
50         Graphics graphics = image.getGraphics();
51         
52         //设置背景色
53         graphics.setColor(Color.WHITE);
54         graphics.fillRect(0, 0, 80, 30);
55         
56         //设置写入数据的颜色和字体
57         graphics.setColor(Color.BLACK);
58         graphics.setFont(new Font(null, Font.BOLD, 20));
59         
60         //像图片上写数据
61         String num = makeNum();
62         
63         //把随机生成的数值,保存到session中
64         request.getSession().setAttribute("checkcode", num);
65         graphics.drawString(num, 0, 20);
66         
67         //把写好数据的图片输出给浏览器
68         ImageIO.write(image, "jpg", response.getOutputStream());
69         
70         
71     }
72 
73     /**
74      * 功能:随机生成7位数字
75      * @return
76      */
77     private String makeNum() {
78         Random random = new Random();
79         //9999999可以生成7位数
80         String num = random.nextInt(9999999)+"";
81         StringBuffer stringBuffer = new StringBuffer();
82         //如果不够指定位数则补0
83         for(int i=0;i<7-num.length();i++) {
84             stringBuffer.append("0");
85         }
86         num = stringBuffer.toString() + num;
87         return num;
88     }
89 
90     /**
91      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
92      */
93     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
94         // TODO Auto-generated method stub
95         doGet(request, response);
96     }
97 
98 }

4

 

 

 

以上是关于javaweb之验证码验证技术的主要内容,如果未能解决你的问题,请参考以下文章

JavaWeb中验证码的实现

JavaWeb——图片验证码技术

JavaWeb 之 重复提交表单和验证码相关的问题!

JAVAWEB开发之HttpServletResponse和HttpServletRequest详解(下)(各种乱码验证码重定向和转发)

Javaweb 响应——生成验证码

Javaweb 响应——生成验证码