Servlet生成验证码图片
1
package
com.logcd.servlet;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics2D;
6 import java.awt.image.BufferedImage;
7 import java.util.Random;
8 import javax.imageio.ImageIO;
9 import javax.servlet. * ;
10 import java.io. * ;
11 import javax.servlet.http. * ;
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16
17 @SuppressWarnings( " serial " )
18 public class RandomCode extends HttpServlet {
19
20 public void doGet(HttpServletRequest request, HttpServletResponse response)
21 throws ServletException, IOException {
22
23 this .doPost(request, response);
24 }
25
26 public void doPost(HttpServletRequest request, HttpServletResponse response)
27 throws ServletException, IOException {
28
29 // 验证码图片的宽度。
30 int width = 70 ;
31 // 验证码图片的高度。
32 int height = 30 ;
33 BufferedImage buffImg = new BufferedImage(width, height, 34 BufferedImage.TYPE_INT_RGB);
35 Graphics2D g = buffImg.createGraphics();
36
37 // 创建一个随机数生成器类。 38 Random random = new Random(); 39 40 // 设定图像背景色(因为是做背景,所以偏淡)
41 g.setColor(getRandColor( 200 , 250 ));
42 g.fillRect( 0 , 0 , width, height);
43 // 创建字体,字体的大小应该根据图片的高度来定。
44 Font font = new Font( " Times New Roman " , Font.HANGING_BASELINE, 28 ); 45 // 设置字体。
46 g.setFont(font); 47 48 // 画边框。 49 g.setColor(Color.BLACK); 50 g.drawRect(0, 0, width - 1, height - 1);
51 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
52 // g.setColor(Color.GRAY);
53 g.setColor(getRandColor( 160 , 200 ));
54 for ( int i = 0 ; i < 155 ; i ++ ) {
55 int x = random.nextInt(width);
56 int y = random.nextInt(height);
57 int xl = random.nextInt( 12 );
58 int yl = random.nextInt( 12 );
59 g.drawLine(x, y, x + xl, y + yl);
60 }
61
62 // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
63 StringBuffer randomCode = new StringBuffer();
64
65 // 设置默认生成4个验证码
66 int length = 4 ;
67 // 设置备选验证码:包括"a-z"和数字"0-9" 68 String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
69
70 int size = base.length();
71
72 // 随机产生4位数字的验证码。
73 for ( int i = 0 ; i < length; i ++ ) { 74 // 得到随机产生的验证码数字。 75 int start = random.nextInt(size);
76 String strRand = base.substring(start, start + 1 );
77
78 // 用随机产生的颜色将验证码绘制到图像中。
79 // 生成随机颜色(因为是做前景,所以偏深) 80 // g.setColor(getRandColor(1, 100)); 81
82 // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
83 g.setColor( new Color( 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 )));
84
85 g.drawString(strRand, 15 * i + 6 , 24 );
86
87 // 将产生的四个随机数组合在一起。
88 randomCode.append(strRand);
89 }
90 // 将四位数字的验证码保存到Session中。
91 HttpSession session = request.getSession();
92 session.setAttribute( " rand " , randomCode.toString());
93
94 // 图象生效
95 g.dispose();
96
97 // 禁止图像缓存。
98 response.setHeader( " Pragma " , " no-cache " );
99 response.setHeader( " Cache-Control " , " no-cache " );
100 response.setDateHeader( " Expires " , 0 );
101
102 response.setContentType( " image/jpeg " );
103
104 // 将图像输出到Servlet输出流中。105 ServletOutputStream sos = response.getOutputStream();
106 ImageIO.write(buffImg, " jpeg " , sos);
107 sos.flush();
108 sos.close();
109
110 }
111
112 Color getRandColor( int fc, int bc) { // 给定范围获得随机颜色
113 Random random = new Random();
114 if (fc > 255 )
115 fc = 255 ;
116 if (bc > 255 )
117 bc = 255 ;
118 int r = fc + random.nextInt(bc - fc);
119 int g = fc + random.nextInt(bc - fc);
120 int b = fc + random.nextInt(bc - fc);
121 return new Color(r, g, b);
122 }
123
124 }
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics2D;
6 import java.awt.image.BufferedImage;
7 import java.util.Random;
8 import javax.imageio.ImageIO;
9 import javax.servlet. * ;
10 import java.io. * ;
11 import javax.servlet.http. * ;
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16
17 @SuppressWarnings( " serial " )
18 public class RandomCode extends HttpServlet {
19
20 public void doGet(HttpServletRequest request, HttpServletResponse response)
21 throws ServletException, IOException {
22
23 this .doPost(request, response);
24 }
25
26 public void doPost(HttpServletRequest request, HttpServletResponse response)
27 throws ServletException, IOException {
28
29 // 验证码图片的宽度。
30 int width = 70 ;
31 // 验证码图片的高度。
32 int height = 30 ;
33 BufferedImage buffImg = new BufferedImage(width, height, 34 BufferedImage.TYPE_INT_RGB);
35 Graphics2D g = buffImg.createGraphics();
36
37 // 创建一个随机数生成器类。 38 Random random = new Random(); 39 40 // 设定图像背景色(因为是做背景,所以偏淡)
41 g.setColor(getRandColor( 200 , 250 ));
42 g.fillRect( 0 , 0 , width, height);
43 // 创建字体,字体的大小应该根据图片的高度来定。
44 Font font = new Font( " Times New Roman " , Font.HANGING_BASELINE, 28 ); 45 // 设置字体。
46 g.setFont(font); 47 48 // 画边框。 49 g.setColor(Color.BLACK); 50 g.drawRect(0, 0, width - 1, height - 1);
51 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
52 // g.setColor(Color.GRAY);
53 g.setColor(getRandColor( 160 , 200 ));
54 for ( int i = 0 ; i < 155 ; i ++ ) {
55 int x = random.nextInt(width);
56 int y = random.nextInt(height);
57 int xl = random.nextInt( 12 );
58 int yl = random.nextInt( 12 );
59 g.drawLine(x, y, x + xl, y + yl);
60 }
61
62 // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
63 StringBuffer randomCode = new StringBuffer();
64
65 // 设置默认生成4个验证码
66 int length = 4 ;
67 // 设置备选验证码:包括"a-z"和数字"0-9" 68 String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
69
70 int size = base.length();
71
72 // 随机产生4位数字的验证码。
73 for ( int i = 0 ; i < length; i ++ ) { 74 // 得到随机产生的验证码数字。 75 int start = random.nextInt(size);
76 String strRand = base.substring(start, start + 1 );
77
78 // 用随机产生的颜色将验证码绘制到图像中。
79 // 生成随机颜色(因为是做前景,所以偏深) 80 // g.setColor(getRandColor(1, 100)); 81
82 // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
83 g.setColor( new Color( 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 )));
84
85 g.drawString(strRand, 15 * i + 6 , 24 );
86
87 // 将产生的四个随机数组合在一起。
88 randomCode.append(strRand);
89 }
90 // 将四位数字的验证码保存到Session中。
91 HttpSession session = request.getSession();
92 session.setAttribute( " rand " , randomCode.toString());
93
94 // 图象生效
95 g.dispose();
96
97 // 禁止图像缓存。
98 response.setHeader( " Pragma " , " no-cache " );
99 response.setHeader( " Cache-Control " , " no-cache " );
100 response.setDateHeader( " Expires " , 0 );
101
102 response.setContentType( " image/jpeg " );
103
104 // 将图像输出到Servlet输出流中。105 ServletOutputStream sos = response.getOutputStream();
106 ImageIO.write(buffImg, " jpeg " , sos);
107 sos.flush();
108 sos.close();
109
110 }
111
112 Color getRandColor( int fc, int bc) { // 给定范围获得随机颜色
113 Random random = new Random();
114 if (fc > 255 )
115 fc = 255 ;
116 if (bc > 255 )
117 bc = 255 ;
118 int r = fc + random.nextInt(bc - fc);
119 int g = fc + random.nextInt(bc - fc);
120 int b = fc + random.nextInt(bc - fc);
121 return new Color(r, g, b);
122 }
123
124 }
配置
1
<
servlet
>
2 < servlet - name > RandomCode </ servlet - name >
3 < servlet - class > com.logcd.servlet.RandomCode </ servlet - class >
4 </ servlet >
5 < servlet - mapping >
6 < servlet - name > RandomCode </ servlet - name >
7 < url - pattern >/ randomCode </ url - pattern >
8 </ servlet - mapping >
2 < servlet - name > RandomCode </ servlet - name >
3 < servlet - class > com.logcd.servlet.RandomCode </ servlet - class >
4 </ servlet >
5 < servlet - mapping >
6 < servlet - name > RandomCode </ servlet - name >
7 < url - pattern >/ randomCode </ url - pattern >
8 </ servlet - mapping >
调用
1
<
meta http
-
equiv
=
"
Content-Type
"
content
=
"
text/html; charset=gb2312
"
/>
2 < meta http - equiv = " pragma " content = " no-cache " />
3 < meta http - equiv = " cache-control " content = " no-cache " />
4 < meta http - equiv = " expires " content = " 0 " />
5
6 < iframe src = " http://127.0.0.1/js_test/randomCode " id = " codeFrame " name = " codeFrame " frameborder = " no " border = " 0 " marginwidth = " 0 "
7 marginheight = " 0 " scrolling = " no " allowtransparency = " yes " height = " 35 " width = " 102 " ></ iframe >
8 < a href = " javascript:void(0); " onclick = " refreshCode(); " > 看不清,换一张 </ a >
9 < br >
10 < span id = " codeImg " >< img border = 0 src = " randomCode " ></ span >
11 < a href = " javascript:void(0); " onclick = " reloadCode() " > 看不清,再换一张 </ a >
2 < meta http - equiv = " pragma " content = " no-cache " />
3 < meta http - equiv = " cache-control " content = " no-cache " />
4 < meta http - equiv = " expires " content = " 0 " />
5
6 < iframe src = " http://127.0.0.1/js_test/randomCode " id = " codeFrame " name = " codeFrame " frameborder = " no " border = " 0 " marginwidth = " 0 "
7 marginheight = " 0 " scrolling = " no " allowtransparency = " yes " height = " 35 " width = " 102 " ></ iframe >
8 < a href = " javascript:void(0); " onclick = " refreshCode(); " > 看不清,换一张 </ a >
9 < br >
10 < span id = " codeImg " >< img border = 0 src = " randomCode " ></ span >
11 < a href = " javascript:void(0); " onclick = " reloadCode() " > 看不清,再换一张 </ a >
1
function $(id){
2 return document.getElementById(id);
3 }
4
5 /** 刷新iframe* */
6 function refreshCode(){
7 window.frames[ " codeFrame " ].location.reload();
8 }
9
10 /** 替换图片* */
11 function reloadCode(){
12 $( " codeImg " ).innerHTML = " <img border=0 src='randomCode'> " ;
13 }
2 return document.getElementById(id);
3 }
4
5 /** 刷新iframe* */
6 function refreshCode(){
7 window.frames[ " codeFrame " ].location.reload();
8 }
9
10 /** 替换图片* */
11 function reloadCode(){
12 $( " codeImg " ).innerHTML = " <img border=0 src='randomCode'> " ;
13 }
本文转自 wws5201985 51CTO博客,原文链接:http://blog.51cto.com/wws5201985/735595,如需转载请自行联系原作者