注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Computer Science

I Pressed My Words Here. Will You Read ?

 
 
 

日志

 
 

java实现登录验证码生成及验证  

2017-03-28 23:49:35|  分类: My Projects |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
最近又遇到需要生成验证码的需求。记得以前用C#写过。不过这次是用java。于是Google了下,
并加以优化:
VerifyCodeServlet.java:

  1 package com.163.blog.computerscience.controller;
  2 
  3 import org.springframework.stereotype.Controller;
  4 import org.springframework.web.bind.annotation.RequestMapping;
  5 import org.springframework.web.bind.annotation.RequestMethod;
  6 
  7 import javax.imageio.ImageIO;
  8 import javax.servlet.ServletException;
  9 import javax.servlet.ServletOutputStream;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 import javax.servlet.http.HttpSession;
 14 import java.awt.*;
 15 import java.awt.image.BufferedImage;
 16 import java.util.Random;
 17 
 18 /**
 19  * Created by will on 2017/3/28.
 20  */
 21 @Controller
 22 public class VerifyCodeServlet
 23                 extends HttpServlet {
 24         // 验证码图片的宽度。
 25         private int width     = 60;
 26         // 验证码图片的高度。
 27         private int height    = 20;
 28         // 验证码字符个数
 29         private int codeCount = 4;
 30         private int x         = 0;
 31         // 字体高度
 32         private int fontHeight;
 33         private int codeY;
 34         char[] codeSequence = {'A''C''D''E''F''G''H''J',
 35                         'K''L''M''N''P''Q''R''S''T''W',
 36                         'X''Y''3''4''6''7''9'};
 37 
 38         /**
 39          * 初始化验证图片属性
 40          */
 41         public void initImgProperties() throws ServletException {
 42                 // 从web.xml中获取初始信息
 43                 // 宽度
 44                 String strWidth = "200";
 45                 // 高度
 46                 String strHeight = "40";
 47                 // 字符个数
 48                 String strCodeCount = "4";
 49                 // 将配置的信息转换成数值
 50                 try {
 51                         if (strWidth != null && strWidth.length() != 0) {
 52                                 width = Integer.parseInt(strWidth);
 53                         }
 54                         if (strHeight != null && strHeight.length() != 0) {
 55                                 height = Integer.parseInt(strHeight);
 56                         }
 57                         if (strCodeCount != null && strCodeCount.length() != 0) {
 58                                 codeCount = Integer.parseInt(strCodeCount);
 59                         }
 60                 } catch (NumberFormatException e) {
 61                 }
 62                 x = width / (codeCount + 2);
 63                 fontHeight = height * 2 / 3;
 64                 codeY = height - 4;
 65         }
 66 
 67         @RequestMapping(value = "admin/verifyCode", method = RequestMethod.GET)
 68         public void service(HttpServletRequest req, HttpServletResponse resp)
 69                         throws ServletException, java.io.IOException {
 70                 initImgProperties();
 71                 // 定义图像buffer
 72                 BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 73                 Graphics2D g = buffImg.createGraphics();
 74                 // 创建一个随机数生成器类
 75                 Random random = new Random();
 76                 // 将图像填充为白色
 77                 g.setColor(Color.WHITE);
 78                 g.fillRect(00, width, height);
 79                 // 创建字体,字体的大小应该根据图片的高度来定。
 80                 Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
 81                 // 设置字体。
 82                 g.setFont(font);
 83                 // 画边框。
 84                 g.setColor(Color.BLACK);
 85                 g.drawRect(00, width - 1, height - 1);
 86                 int red = 0, green = 0, blue = 0;
 87                 int edageInt = 150;
 88                 // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
 89                 g.setColor(Color.BLACK);
 90                 for (int i = 0; i < 100; i++) {
 91                         red = random.nextInt(55) + edageInt;
 92                         green = random.nextInt(55) + edageInt;
 93                         blue = random.nextInt(55) + edageInt;
 94                         g.setColor(new Color(red, green, blue));
 95                         int x = random.nextInt(width);
 96                         int y = random.nextInt(height);
 97                         int xl = random.nextInt(12);
 98                         int yl = random.nextInt(12);
 99                         g.drawLine(x, y, x + xl, y + yl);
100                 }
101                 // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
102                 StringBuffer randomCode = new StringBuffer();
103                 // 随机产生codeCount数字的验证码。
104                 for (int i = 0; i < codeCount; i++) {
105                         // 得到随机产生的验证码数字。
106                         String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
107                         // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
108                         int baseInt = (edageInt / codeCount);
109                         int radomInt = (i % 2 == 0 ? i + 1 : i - 1);
110                         red = random.nextInt(baseInt) + baseInt * radomInt;
111                         green = random.nextInt(baseInt) + baseInt * radomInt;
112                         blue = random.nextInt(baseInt) + baseInt * radomInt;
113                         // 用随机产生的颜色将验证码绘制到图像中。
114                         g.setColor(new Color(red, green, blue));
115                         double randomNumber = ((double)random.nextInt(4)) / 10 + 0.2;
116                         randomNumber = randomNumber * ((randomNumber * 10 % 2) == 0 ? -1 : 1);
117                         g.rotate(randomNumber, ((i + 1) * x + fontHeight / 2), (height / 2));
118                         g.drawString(strRand, ((i + 1) * x), (codeY));
119                         // 将产生的四个随机数组合在一起。
120                         randomCode.append(strRand);
121                         g.rotate(-randomNumber, ((i + 1) * x + fontHeight / 2), (height / 2));
122                 }
123                 // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
124                 g.setColor(Color.BLACK);
125                 for (int i = 0; i < 20; i++) {
126                         red = random.nextInt(55) + i;
127                         green = random.nextInt(55) + i;
128                         blue = random.nextInt(55) + i;
129                         g.setColor(new Color(red, green, blue));
130                         int x = random.nextInt(width);
131                         int y = random.nextInt(height);
132                         int xl = random.nextInt(12 * (i % 3 + 1));
133                         int yl = random.nextInt(12 * (i % 3 + 1));
134                         g.drawLine(x, y, x + xl, y + yl);
135                 }
136                 // 将四位数字的验证码保存到Session中。
137                 HttpSession session = req.getSession();
138                 session.setAttribute("validateCode", randomCode.toString());
139                 // 禁止图像缓存。
140                 resp.setHeader("Pragma""no-cache");
141                 resp.setHeader("Cache-Control""no-cache");
142                 resp.setDateHeader("Expires"0);
143                 resp.setContentType("image/jpeg");
144                 // 将图像输出到Servlet输出流中。
145                 ServletOutputStream sos = resp.getOutputStream();
146                 ImageIO.write(buffImg, "jpeg", sos);
147                 sos.close();
148         }
149 }
150 

ResultServlet.java:
package com.163.blog.computerscience.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by will on 2017/3/28.
 */
@Controller
public class ResultServlet {
        @RequestMapping(value = "admin/validateCode", method = RequestMethod.POST)
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                response.setContentType("text/html;charset=utf-8");
                String validateC = (String) request.getSession().getAttribute("validateCode");
                String veryCode = request.getParameter("c");
                PrintWriter out = response.getWriter();
                if (veryCode == null || "".equals(veryCode)) {
                        out.println("验证码为空");
                } else {
                        if (validateC.toUpperCase().equals(veryCode.toUpperCase())) {
                                out.println("验证码正确");
                        } else {
                                out.println("验证码错误");
                        }
                }
                out.flush();
                out.close();
        }
}


LoginController.java:
package com.163.blog.computerscience.web.controller;

import com.163.blog.computerscience.common.util.CookieUtils;
import com.163.blog.computerscience.common.util.RedisUtils;
import com.163.blog.computerscience.upms.data.UserData;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("admin/user")
public class LoginController {

        @Autowired
        private UserData userData;
        
        @RequestMapping(value="login")
        public String userLogin(String userName,String userPassword,String validationCode,
                        HttpServletResponse response,
                        HttpServletRequest request,
                        Model model,
                        @RequestParam(name="thoughts",required=false) String thoughts
                                ){
                try {
                        // 验证码
                        response.setContentType("text/html;charset=utf-8");
                        String validateC = (String) request.getSession().getAttribute("validateCode");
                        String veryCode = validationCode;
                        if (veryCode == null || "".equals(veryCode)) {
                                throw new RuntimeException("验证码为空");
                        } else {
                                if (validateC.toUpperCase().equals(veryCode.toUpperCase())) {
                                        // throw new RuntimeException("验证码正确");
                                } else {
                                        throw new RuntimeException("验证码错误");
                                }
                        }
                        if(StringUtils.isBlank(userName)||StringUtils.isBlank(userPassword)){
                                throw new RuntimeException("用户名密码为空");
                        }// else{}
                        userData.userLogin(userName, userPassword,request,response);
                        // return "index/index";
                        return "index/index.jsp?" + (StringUtils.isNotBlank(thoughts)?("thoughts="+thoughts): "");
                } catch (Exception e) {
                        model.addAttribute("msg", e.getMessage());
                        // return "user/login";
                        return "user/login.jsp?" + (StringUtils.isNotBlank(thoughts)?("thoughts="+thoughts): "");
                }
        }
        
        @RequestMapping(value="loginOut")
        public String loginOut(HttpServletRequest request,
                               @RequestParam(name="thoughts",required=false) String thoughts
                               ){
                String login= CookieUtils.getCookie(request, CookieUtils.LONG_COOKIE);
            RedisUtils.del(login);
                // return "user/login";
                return "user/login" + (StringUtils.isNotBlank(thoughts)?(".jsp?thoughts="+thoughts): "");
        }
}

login.jsp:
END
  评论这张
 
阅读(37)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017