e.FLY

Java Servlet生成验证码

生成验证码类

View Code

  1 package com.service.test;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.awt.Color;
6 import java.awt.Font;
7 import java.awt.Graphics2D;
8 import java.awt.image.BufferedImage;
9 import java.util.Random;
10 import javax.imageio.ImageIO;
11 import javax.servlet.*;
12 import java.io.*;
13 import javax.servlet.http.*;
14 import javax.servlet.ServletException;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18
19 /**
20 * 生成验证码
21 * @author E.FLY
22 * @date 2012-3-12 上午09:44:02
23 * @package_name com.service.test
24 */
25 public class VerificationCode extends HttpServlet {
26
27 /**
28 * Constructor of the object.
29 */
30 public VerificationCode() {
31 super();
32 }
33
34 /**
35 * Destruction of the servlet. <br>
36 */
37 public void destroy() {
38 super.destroy(); // Just puts "destroy" string in log
39 // Put your code here
40 }
41
42
43 public void doGet(HttpServletRequest request, HttpServletResponse response)
44 throws ServletException, IOException {
45
46 doPost(request, response);
47 }
48
49 /**
50 * The doPost method of the servlet. <br>
51 *
52 * This method is called when a form has its tag value method equals to post.
53 *
54 * @param request the request send by the client to the server
55 * @param response the response send by the server to the client
56 * @throws ServletException if an error occurred
57 * @throws IOException if an error occurred
58 */
59 public void doPost(HttpServletRequest request, HttpServletResponse response)
60 throws ServletException, IOException {
61 // 验证码图片的宽度。
62 int width = 70;
63 // 验证码图片的高度。
64 int height = 30;
65 BufferedImage buffImg = new BufferedImage(width, height,
66 BufferedImage.TYPE_INT_RGB);
67 Graphics2D g = buffImg.createGraphics();
68
69 // 创建一个随机数生成器类。
70 Random random = new Random();
71
72 // 设定图像背景色(因为是做背景,所以偏淡)
73 g.setColor(getRandColor(200, 250));
74 g.fillRect(0, 0, width, height);
75 // 创建字体,字体的大小应该根据图片的高度来定。
76 Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
77 // 设置字体。
78 g.setFont(font);
79
80 // 画边框。
81 g.setColor(Color.BLACK);
82 g.drawRect(0, 0, width - 1, height - 1);
83 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
84 //g.setColor(Color.GRAY);
85 g.setColor(getRandColor(160,200));
86 for (int i = 0; i < 155; i++) {
87 int x = random.nextInt(width);
88 int y = random.nextInt(height);
89 int xl = random.nextInt(12);
90 int yl = random.nextInt(12);
91 g.drawLine(x, y, x + xl, y + yl);
92 }
93
94 // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
95 StringBuffer randomCode = new StringBuffer();
96
97 // 设置默认生成4个验证码
98 int length = 4;
99 // 设置备选验证码:包括"a-z"和数字"0-9"
100 String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
101
102 int size = base.length();
103
104 // 随机产生4位数字的验证码。
105 for (int i = 0; i < length; i++) {
106 // 得到随机产生的验证码数字。
107 int start = random.nextInt(size);
108 String strRand = base.substring(start, start + 1);
109
110 // 用随机产生的颜色将验证码绘制到图像中。
111 // 生成随机颜色(因为是做前景,所以偏深)
112 //g.setColor(getRandColor(1, 100));
113
114 //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
115 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
116
117 g.drawString(strRand, 15 * i + 6, 24);
118
119 // 将产生的四个随机数组合在一起。
120 randomCode.append(strRand);
121 }
122
123 // 将四位数字的验证码保存到Session中。
124 HttpSession session = request.getSession();
125 session.setAttribute("vcRand", randomCode.toString());
126 //图象生效
127 g.dispose();
128
129 // 禁止图像缓存。
130 response.setHeader("Pragma", "no-cache");
131 response.setHeader("Cache-Control", "no-cache");
132 response.setDateHeader("Expires", 0);
133
134 response.setContentType("image/jpeg");
135
136 // 将图像输出到Servlet输出流中。
137 ServletOutputStream sos = response.getOutputStream();
138 ImageIO.write(buffImg, "jpeg", sos);
139 sos.flush();
140 sos.close();
141
142 }
143
144 Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
145 Random random = new Random();
146 if (fc > 255)
147 fc = 255;
148 if (bc > 255)
149 bc = 255;
150 int r = fc + random.nextInt(bc - fc);
151 int g = fc + random.nextInt(bc - fc);
152 int b = fc + random.nextInt(bc - fc);
153 return new Color(r, g, b);
154 }
155
156
157 public void init() throws ServletException {
158 super.init();
159 }
160
161 }

显示验证的JSP

View Code

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2 <%
3 String path = request.getContextPath();
4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
5 request.setAttribute("path",path);
6 %>
7
8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
9 <html>
10 <head>
11 <base href="<%=basePath%>">
12
13 <title>验证码</title>
14
15 <meta http-equiv="pragma" content="no-cache">
16 <meta http-equiv="cache-control" content="no-cache">
17 <meta http-equiv="expires" content="0">
18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19 <meta http-equiv="description" content="This is my page">
20 <!--
21 <link rel="stylesheet" type="text/css" href="styles.css">
22 -->
23 <script type="text/javascript" src="${path}/js/jquery-1.6.2.js"></script>
24 <script type="text/javascript">
25 function $(id){
26 return document.getElementById(id);
27 }
28
29 /**刷新iframe**/
30 function refreshCode(){
31 window.frames["codeFrame"].location.reload();
32 }
33
34 /**替换图片**/
35 function reloadCode(){
36 $("codeImg").innerHTML = "<img border=0 src='${path}/VerificationCode'>";
37 }
38
39 </script>
40
41 </head>
42
43 <body>
44 <iframe src="${path}/VerificationCode" id="codeFrame" name="codeFrame" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" height="35" width="102">
45 </iframe>
46 <a href="javascript:void(0);" onclick="refreshCode();">看不清,换一张</a><br>
47 <input type="text" id="vcRand"/><input type="button" value="提交" onclick="vcRand()"/>
48 <span id="codeImg"><img border=0 src="${path}/VerificationCode"></span>
49 <a href="javascript:void(0);" onclick="reloadCode()">看不清,再换一张</a>
50
51 </body>
52 </html>

验证的Servlet

View Code

 1 package com.service.test;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.Map;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import b2c.members.exception.MemberException;
13 import b2c.members.model.Member;
14
15 import com.opensymphony.xwork2.ActionContext;
16 import common.json.JSONException;
17 import common.json.JSONObject;
18
19 /**
20 * 验证码验证
21 * @author E.FLY
22 * @date 2012-3-12 上午09:42:42
23 * @package_name com.service.test
24 */
25 public class Verification extends HttpServlet {
26
27 /**
28 * Constructor of the object.
29 */
30 public Verification() {
31 super();
32 }
33
34
35 public void doGet(HttpServletRequest request, HttpServletResponse response)
36 throws ServletException, IOException {
37
38 doPost(request, response);
39 }
40
41 public void doPost(HttpServletRequest request, HttpServletResponse response)
42 throws ServletException, IOException {
43
44 PrintWriter out = response.getWriter();
45 /**
46 * 会员登录
47 */
48 ActionContext context = ActionContext.getContext();
49 Map<String, Object> session = context.getSession();
50 public void memberLogin(){
51 JSONObject json = new JSONObject();
52 Member memberLogin = null;
53 try {
54 memberLogin = memberService.memberLogin(member);
55 if(memberLogin != null){
56 String vcR = session.get("vcRand").toString().toUpperCase();//获得验证码
57 if(vcR.equals(member.getVcRand().toUpperCase())){
58 session.put("memberLogin", memberLogin);
59 json.put("b", true);
60 json.put("vc", true);
61 }else{
62 json.put("vc", false);
63 }
64 }else{
65 json.put("b", false);
66 }
67 }catch (MemberException e) {
68 e.printStackTrace();
69 } catch (JSONException e) {
70 e.printStackTrace();
71 }
72 super.print(json.toString());
73 }
74 out.flush();
75 out.close();
76 }
77
78 }




posted on 2012-03-13 20:37  e.FLY  阅读(432)  评论(0)    收藏  举报