动手实现随机验证码

见过好几种类型的验证码,一开始觉得验证码的生成很神奇,后来发现验证码也是可以用Java轻松实现的。今天就来做一做这件事情。

首先,来写一个画验证码图片的Java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.xxx.validationCode;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class ValidationCode extends HttpServlet{
     
     public static String getValidationCodes(OutputStream os){
         char codeTable[]={
                 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' ,
                 'm' , 'n' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' ,
                 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' ,
                 'M' , 'N' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' ,
                 '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9'
             };    //判断时大小写不区分,另外,没有使用'O'和'0',也是怕混淆的麻烦   
         
         BufferedImage image = new BufferedImage( 60 , 20 ,
                                     BufferedImage.TYPE_INT_RGB);
         //生成60×20的RGB图片
         Graphics graphic = image.getGraphics();
         //背景色
         graphic.setColor( new Color( 0xDCDCDC ));
         graphic.fillRect( 0 , 0 , 60 , 20 );
         
         char codes[] = new char [ 4 ];
         //随机产生验证码
         for ( int i= 0 ; i<= 3 ; i++) {
             codes[i] = codeTable[( int )(codeTable.length*Math.random())];
         }
         
         //把字画上去
         graphic.setColor(Color.BLACK);
         graphic.setFont( new Font( "Arial" , Font.BOLD, 16 ));
         for ( int i= 0 ; i<= 3 ; i++){
             graphic.drawChars(codes, i, 1 , 2 + 15 *i, 15 +i);
             //把codes[i]画到坐标为[10+5*i,15+i]的地方去
         }
         
         //15个干扰点
         Random rand = new Random();
         for ( int i= 0 ;i< 15 ;i++)
             graphic.drawOval(rand.nextInt( 60 ),rand.nextInt( 20 ), 1 , 1 );
         
         //释放此图形的上下文并释放它所使用的所有系统资源
         graphic.dispose();
         
         try {
             ImageIO.write(image, "JPEG" , os);
         } catch (IOException e) {
             e.printStackTrace();
         }
         
         return new String(codes, 0 ,codes.length);
     }
 
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doPost(request,response);
     }
 
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         request.getSession().setAttribute( "validationCodes" , getValidationCodes(response.getOutputStream()));
     }
     
}

然后,写一个Servlet将生成的图片写入页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.xxx.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.xxx.validationCode.ValidationCode;
 
public class ValidationServlet extends HttpServlet {
 
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doPost(request,response);
     }
 
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         String str = ValidationCode.getValidationCodes(response.getOutputStream());
         request.getSession().setAttribute( "validationCodes" , str);
     }
 
}

接着,在login.jsp中加入如下表单:

1
2
3
4
5
6
7
8
9
10
11
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
< form action = "<%=basePath+" servlet/LoginServlet"%>">
     < img src = "<%=basePath+" servlet/ValidationServlet"%>"/>
     < br >
     < input type = "text" name = "codes" />
     < input type = "submit" />
</ form >

再写进行后台判断的Servlet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.xxx.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginServlet extends HttpServlet {
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doPost(request,response);
     }
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
 
         if (request.getSession().getAttribute( "validationCodes" ).toString().toLowerCase()
                     .equals(request.getParameter( "codes" ).toString().toLowerCase()))
             response.getOutputStream().println( "Right!" );
         else
             response.getOutputStream().println( "Wrong!" );
         
     }
 
}

转载自《四火的唠叨》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值