添加动态验证码

Posted on 2007-07-25 14:26 胡娟 阅读(704) 评论(1)  编辑  收藏
1.用户信息VO包
 1package com.hujuan.VO;
 2
 3public class UserInfo {
 4    private String username;
 5    private String password;
 6    public String getPassword() {
 7        return password;
 8    }

 9    public void setPassword(String password) {
10        this.password = password;
11    }

12    public String getUsername() {
13        return username;
14    }

15    public void setUsername(String username) {
16        this.username = username;
17    }

18}
2.验证登录Dao包
 1package com.hujuan.dao;
 2
 3import com.hujuan.VO.UserInfo;
 4
 5public class UserInfoDao {
 6    public boolean checklogin(UserInfo userinfo){
 7        System.out.println(userinfo.getUsername());
 8        System.out.println(userinfo.getUsername());
 9        if("hujuan".equals(userinfo.getUsername())&&"123".equals(userinfo.getPassword())){
10            return true;
11        }
return false;
12    }

13}
3.生产随机码验证servlet
 1package com.hujuan.servlet;
 2
 3
 4import java.awt.Graphics2D;
 5import java.awt.image.BufferedImage;
 6import java.io.IOException;
 7import java.util.Random;
 8import java.awt.Color;
 9import java.awt.Font;
10import javax.imageio.ImageIO;
11import javax.servlet.ServletException;
12import javax.servlet.ServletOutputStream;
13import javax.servlet.http.HttpServlet;
14import javax.servlet.http.HttpServletRequest;
15import javax.servlet.http.HttpServletResponse;
16import javax.servlet.http.HttpSession;
17
18public class RandomCodeServler extends HttpServlet {
19    private int width = 60;    //验证图片的宽度
20    private int height = 20//验证图片的高度
21    @Override
22    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
23        
24        BufferedImage buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
25        
26        Graphics2D g = buffImg.createGraphics();
27    
28    
29    //创建一个随机数生产器类
30    Random random = new Random();
31    
32    g.setColor(Color.WHITE);
33    g.fillRect(00, width, height);
34    
35    //创建字体,字体的大小应该根据图片的高度来定
36    Font font = new Font("123123",Font.PLAIN,18);
37    //设置字体
38    g.setFont(font);
39    //画边框
40    g.setColor(Color.BLACK);
41    g.drawRect(00, width-1,height-1);
42    //随机生产100条干扰线,使图像中的验证吗不易被其他程序探测到
43    g.setColor(Color.GRAY);
44    for(int i=0;i<100;i++){
45        int x = random.nextInt(width);
46        int y = random.nextInt(height);
47        int x1 = random.nextInt(12);
48        int y1 = random.nextInt(12);
49        g.drawLine(x, y, x+x1, y+y1);
50    }

51    //randomCode 用于保存随机产生的验证码,以便用户登录后进行验证
52    StringBuffer randomCode = new StringBuffer();
53    int red = 0,green = 0,blue = 0;
54    //随机产生4位数字的验证码
55    for(int i = 0;i<4;i++){
56        //得到随机产生的验证码数字
57        String strRand = String.valueOf(random.nextInt(10));
58        
59        //产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同
60        red = random.nextInt(110);
61        green = random.nextInt(50);
62        blue = random.nextInt(50);
63        
64        //用随机产生的颜色将验证码绘制到图像中
65        g.setColor(new Color(red,green,blue));
66        g.drawString(strRand, 13*i+616);
67        //将产生的四个随机数组合在一起
68        randomCode.append(strRand);
69    }

70    //将四位数字的验证码保存到session中
71    HttpSession session = req.getSession();
72    session.setAttribute("randomCode", randomCode.toString());
73    //禁止图像缓存
74//    resp.setHeader("Pragma", "no-cache");
75//    resp.setHeader("Cache-Control", "no-cache");
76//    resp.setDateHeader("Expires", 0);
77//    resp.setContentType("image/jpeg");
78    //将图像输出到servlet输出流中
79    ServletOutputStream out = resp.getOutputStream();
80    ImageIO.write(buffImg,"jpeg",out);
81    out.close();
82    }

83}

84
4.验证登录的servlet
 1package com.hujuan.servlet;
 2
 3import java.io.IOException;
 4import java.io.PrintWriter;
 5import javax.servlet.ServletException;
 6import javax.servlet.http.HttpServlet;
 7import javax.servlet.http.HttpServletRequest;
 8import javax.servlet.http.HttpServletResponse;
 9import javax.servlet.http.HttpSession;
10import com.hujuan.VO.UserInfo;
11import com.hujuan.dao.UserInfoDao;
12
13public class LoginCheckServlet extends HttpServlet {
14
15    public void doPost(HttpServletRequest request, HttpServletResponse response)
16            throws ServletException, IOException {
17
18        //request.setCharacterEncoding("gb2312");
19        response.setCharacterEncoding("gb2312");
20        
21        response.setContentType("text/html; charset = gb2312");
22        PrintWriter out = response.getWriter();
23        
24        HttpSession session = request.getSession();
25        String randomCode =(String)session.getAttribute("randomCode");
26        
27        if(null == randomCode){
28            response.sendRedirect("index.jsp");
29            return;
30        }

31        
32        String reqRandom = request.getParameter("randomcode");//meiyou huode
33
34        UserInfo userinfo = new UserInfo();
35        String name = request.getParameter("username");
36        String password = request.getParameter("password");
37        
38        userinfo.setUsername(name);
39        userinfo.setPassword(password);
40        
41        
42//        System.out.println(reqRandom);
43//        System.out.println(randomCode);
44//        System.out.println(name);
45//        System.out.println(password);
46        if(randomCode.equals(reqRandom)){
47            UserInfoDao userdao = new UserInfoDao();
48            if(userdao.checklogin(userinfo)){
49                response.sendRedirect("succ.jsp");
50            }
else{
51                out.println("请检查用户名和密码");
52            }

53        }
else{
54            out.println("请检查验证码");
55        }

56    }

57
58}

59
5.登录页面
 1<%@ page language="java" import="java.util.*" 
 2    contentType="text/html; charset=gb2312"%>
 3<%
 4    String path = request.getContextPath();
 5    String basePath = request.getScheme() + "://"
 6            + request.getServerName() + ":" + request.getServerPort()
 7            + path + "/";
 8%>
 9
10<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11<html>
12    <head>
13        <base href="<%=basePath%>">
14
15        <title>My JSP 'Login.jsp' starting page</title>
16
17        <meta http-equiv="pragma" content="no-cache">
18        <meta http-equiv="cache-control" content="no-cache">
19        <meta http-equiv="expires" content="0">
20        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
21        <meta http-equiv="description" content="This is my page">
22        <!--
23    <link rel="stylesheet" type="text/css" href="styles.css">
24    -->
25
26        <style type="text/css">
27<!--
28.text {
29    font-family: "宋体";
30    font-size: 12px;
31    font-style: normal;
32    line-height: 25px;
33    font-weight: normal;
34    font-variant: normal;
35    color: #000000;
36}

37-->
38        </style>
39</head>
40
41    <body>
42        <form method="post" name="login" action="LoginCheckServlet">
43            <p>&nbsp;
44                
45          </p>
46            <table width="40%" border="0" align="center">
47              <tbody>
48                <tr>
49                  <td width="22%" align="right" class="text">&nbsp;用户名 </td>
50                  <td width="37%"><input name="username" type="text" size="20">
51                      <br>
52                  </td>
53                </tr>
54                <tr>
55                  <td align="right" class="text">&nbsp;密 码 </td>
56                  <td><input name="password" type="password" size="20" maxlength="16">
57                  </td>
58                </tr>
59                <tr>
60                  <td align="right" class="text">&nbsp;验证码 </td>
61                  <td><input name="randomcode" type="text" size="5" maxlength="4">
62                      <img src="imgcode"> </td>
63                </tr>
64                <tr>
65                  <td align="right">&nbsp;
66                  <input type="submit" value="提交" name="submit">                  </td>
67                  <td align="center">&nbsp;
68                      <input type="reset" value="重置" name="reset">                  </td>
69                </tr>
70              </tbody>
71          </table>
72        </form>
73    </body>
74</html>
75
6.成功页面
 1<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2<%
 3String path = request.getContextPath();
 4String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5%>
 6
 7<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8<html>
 9  <head>
10    <base href="<%=basePath%>">
11    
12    <title>My JSP 'succ.jsp' starting page</title>
13    
14    <meta http-equiv="pragma" content="no-cache">
15    <meta http-equiv="cache-control" content="no-cache">
16    <meta http-equiv="expires" content="0">    
17    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18    <meta http-equiv="description" content="This is my page">
19    <!--
20    <link rel="stylesheet" type="text/css" href="styles.css">
21    -->
22
23  </head>
24  
25  <body>
26    This is my JSP page. <br>
27  </body>
28</html>
29

Feedback

# re: 添加动态验证码  回复  更多评论   

2012-05-27 22:04 by mable
我觉得很奇怪,为什么我的验证码总是“62”呢?劳烦给我解释一下servlet绘制的验证码图片是怎么放在登陆页面的啊? <img src="imgcode">,imgcode从哪里来?

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 28, comments - 5, trackbacks - 0, articles - 1

Copyright © 胡娟