自己封装的验证码工具类以及登录验证

1.验证码CreateYZMCodeUtils工具类

package com.han.util;

import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.util.Random;  
/** 
 * 生成验证码的工具类 
 * 自己封装的 
 * @author issuser 
 * 
 */  
public class CreateYZMCodeUtils {  
    private Integer width;//验证码图片宽度  
    private Integer height;//验证吗图片高度  
    private Integer num;//验证码的个数  
    private String code;//生成验证码一组字符串  

    private static final Random ran=new Random();//随机数  
    private static CreateYZMCodeUtils createYZMCodeUtils;  
    /** 
     * 通过默认构造初始化参数 
     */  
    private CreateYZMCodeUtils(){  
        width=100;  
        height=30;  
        code="123456789adcdefghijklmnopqrstuvwxyz";  
        num=4;  
    }  
    /** 
     * 利用单利模式创建该验证码工具类 
     * @return 
     */  
    public static CreateYZMCodeUtils getInstance(){  
        if(createYZMCodeUtils==null){  
            createYZMCodeUtils=new CreateYZMCodeUtils();  
        }  
        return createYZMCodeUtils;  
    }  
    public Integer getWidth() {  
        return width;  
    }  

    public void setWidth(Integer width) {  
        this.width = width;  
    }  

    public Integer getHeight() {  
        return height;  
    }  

    public void setHeight(Integer height) {  
        this.height = height;  
    }  

    public Integer getNum() {  
        return num;  
    }  

    public void setNum(Integer num) {  
        this.num = num;  
    }  

    public String getCode() {  
        return code;  
    }  

    public void setCode(String code) {  
        this.code = code;  
    }  

    public static Random getRan() {  
        return ran;  
    }  
    public void setCreateYZMCodeUtils(Integer width,Integer height,Integer num,String code){  
        this.width=width;  
        this.height=height;  
        this.num=num;  
        this.code=code;  
    }  
    public void setCreateYZMCodeUtils(Integer width,Integer height,String code){  
        this.width=width;  
        this.height=height;  
        this.code=code;  
    }  
    /** 
     * 随机生成验证码 
     * @param code 生成验证码的一组字符串 
     * @return 
     */  
    public String getCreateYZMCode(){  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < num; i++) {  
            sb.append(code.charAt(ran.nextInt(code.length())));  
        }  
        return sb.toString();  
    }  
    /** 
     * 生成buffere Image图片 
     * @param finshCode 生成好的验证码字符串 
     * @return 
     */  
    public BufferedImage getCreateYZMImg(String finshCode){  
        // 创建BufferedImage对象  
        BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
        Graphics2D graphic = img.createGraphics();// 创建画笔  
        graphic.setColor(Color.WHITE);// 设置颜色  
        graphic.fillRect(0, 0, width, height);//是用预定的颜色填充一个矩形,得到一个着色的矩形块。  
        graphic.setColor(Color.black);  
        graphic.drawRect(0, 0, width - 1, height - 1);// 画正方形  
        // 设置字体 风格 风格 高度  
        Font font = new Font("宋体", Font.BOLD + Font.ITALIC,(int) (height * 0.8));  
        graphic.setFont(font);  
        for (int i = 0; i < num; i++) {  
            // 随机设置字体RGB颜色  
            graphic.setColor(new Color(ran.nextInt(255), ran.nextInt(255),ran.nextInt(255)));  
            // 画出验证码  
            graphic.drawString(String.valueOf(finshCode.charAt(i)), i* (width /

num) + 4, (int) (height * 0.8));
}
for (int i = 0; i < (width + height); i++) {
// 随机设置字体RGB颜色
graphic.setColor(new Color(ran.nextInt(255), ran.nextInt(255),ran.nextInt(255)));
// 生成干扰点
graphic.drawOval(ran.nextInt(width), ran.nextInt(height), 1, 1);
}
for(int i = 0; i <2; i++){
// 随机设置字体RGB颜色
graphic.setColor(new Color(ran.nextInt(255), ran.nextInt(255),ran.nextInt(255)));
// 随机生成干扰线
graphic.drawLine(0, ran.nextInt(height), width,ran.nextInt(height));
}
return img;
}
}

2.Controller控制器的调用

package com.han.controller;  
import java.awt.image.BufferedImage;  
import java.io.IOException;  
import java.io.OutputStream;  

import javax.annotation.Resource;  
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  

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

import com.han.model.User;  
import com.han.service.UserServ;  
import com.han.util.CreateYZMCodeUtils;  
import com.han.util.Md5Utils;  

@Controller  
public class AdminController {  
    @Resource(name="userServ")  
    private UserServ userServ;  
    @RequestMapping("/admin")  
    public String index() {  
        return "admin/index";  
    }  

    /** 
     * 跳转至登录页面 
     *  
     * @return 
     */  
    @RequestMapping(value = "/login", method = RequestMethod.GET)  
    public String login() {  
        return "admin/login";  
    }  
    /** 
     * 验证登录 
     * @param username 用户名 
     * @param password 登录密码 
     * @param checkCode 验证码 
     * @param session 
     * @return 
     */  
    @RequestMapping(value = "/login", method = RequestMethod.POST)  
    public String login(String username,String password,String checkCode,HttpSession session,Model model) {  
        String code=(String) session.getAttribute("code");  
        User user = this.userServ.loadByUserName(username);  
        if(user==null){  
            model.addAttribute("userError", "用户名或密码不正确!");  
            return "admin/login";  
        }   
        //验证密码  
        String md5 = Md5Utils.Md5(password);  
        if(!user.getPassword().equals(md5)){  
            model.addAttribute("userError", "用户名或密码不正确!");  
            return "admin/login";  
        }  
        if(code!=null && !code.equals(checkCode)){  
            model.addAttribute("codeError", "验证码不正确,请重新输入!");  
            return "admin/login";  
        }  
        session.setAttribute("loginUser", user);  
        return "redirect:/admin";  
    }  

    /** 
     * 生成验证码图片 
     *  
     * @param response 
     * @param session 
     */  
    @RequestMapping("/createYZM")  
    public void createYZM(HttpServletResponse response, HttpSession session) {  
        OutputStream out = null;  
        try {  
            // 设置响应类型  
            response.setContentType("image/jpg");  
            // 获取创建验证码工具类实例  
            CreateYZMCodeUtils yzm = CreateYZMCodeUtils.getInstance();  
            // 获取生成的验证码字符串  
            String code = yzm.getCreateYZMCode();  
            // 将验证码存放在session  
            session.setAttribute("code", code);  
            // 获取验证码图片  
            BufferedImage img = yzm.getCreateYZMImg(code);  
            out = response.getOutputStream();  
            // 通过ImageIO写出图片  
            ImageIO.write(img, "jpg", out);  
            out.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (out != null) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
}  

3.jsp登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resources/css/admin/login.css"/>  
<script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/jquery-1.7.2.min.js"></script>  
<script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/jquery.validate.js"></script>  
<script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/core/jquery.cms.validate.js"></script>  
<title>后台管理登录</title>  
<script type="text/javascript">  
$(function(){  
    $("#myForm").cmsvalidate();  
});  
function reCheckcode(img) {  
        //后面跟一个随机数方便每次请求都是一个新的请求,刷新验证码,防止会在缓存中去验证码图片  
    img.src="createYZM?"+Math.random();  
}  
</script>  
</head>  
<body>  
    <div id="container">  
        <div id="top">  

        </div>  
        <div id="content">  
            <div id="loginForm">  
                   <p style="color: red;margin-left: 98px">${userError}</p>  
                   <form action="" id="myForm"  method="post">  
                    <table cellpadding="0" cellspacing="0" width="380px" id="loginTable">  
                        <tr>  
                            <td align="right" width="90">登录用户:</td>  
                            <td align="left"><input type="text" name="username" size="18"/> </td>  
                        </tr>  
                        <tr>  
                            <td align="right">登录密码:</td>  
                            <td align="left"><input type="password"  name="password" size="18"/></td>  
                        </tr>  
                        <tr>  
                            <td align="right">验证码:</td>  
                            <td align="left">  
                            <input type="text" name="checkCode" id="validateCode" size="10"/>  
                            ${codeError}  
                            </td>  
                        </tr>  
                        <tr>  
                            <td align="left" colspan="2">  
                            <span style="margin-left:94px;cursor:pointer">  
                            <img src="createYZM" onclick="reCheckcode(this)"/></span>  
                            </td>  
                        </tr>  
                        <tr>  
                            <td align="center" colspan="2">  
                                <input type="submit" value="登录">   <input type="reset" value="重置"/>  
                            </td>  
                        </tr>  
                    </table>  
                    </form>  
            </div>  
        </div>  
    </div>      
</body>  
</html>  

转载自:这里写链接内容

展开阅读全文

没有更多推荐了,返回首页