生成登入验证码

1、简单的登入页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form id="loginForm" action="${ctx.contextPath}/login" method="post">
    <div class="row">
        <input style="color: rgb(0, 0, 0);" name="userId" maxlength="50" id="txtUserName2" title="用户名"  type="text" />
    </div>
    <div class="row">
        <input  name="password" id="txtPassword2" type="password"/>
    </div>
    <div id="divValidate2" class="row clearfix">
        <input name="validateCode" maxlength="4" id="txtValidateCode2" type="text"/>
        <img id="imgCheckCode2" alt="看不清楚?换一张" class="validateimg" onclick="reloadImages()"style="cursor: pointer;"/>
    </div>
    
</form>

</body>

<script type="text/javascript">
    $(function () {
        reloadImages();//加载验证码图片
    });
    function reloadImages() {
        var url = "<c:url value='/getCode'/>";
        document.getElementById("imgCheckCode2").src = url + "?Date" + new Date().getTime();
    }
</script>
</html>

2、控制层Controller

 /**
     * 获取验证码
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "getCode", method = RequestMethod.GET)
    public void login_code(HttpServletResponse response) throws Exception {

        String validateCode = VerifyCodeUtil.generateCode(VerifyCodeUtil.TYPE_NUM_UPPER, 4, null);
        setSessionAttr("validateCode", validateCode);
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(validateCode, 90, 30, 10, false, Color.WHITE, null, null, null);
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpeg", sos);
        sos.close();
    }

3、工具类Util

package com.oceansoft.utility;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;


public class VerifyCodeUtil {
    /**
     * 验证码类型为仅数字,即0~9
     */
    public static final int TYPE_NUM_ONLY = 0;

    /**
     * 验证码类型为仅字母,即大小写字母混合
     */
    public static final int TYPE_LETTER_ONLY = 1;

    /**
     * 验证码类型为数字和大小写字母混合
     */
    public static final int TYPE_ALL_MIXED = 2;

    /**
     * 验证码类型为数字和大写字母混合
     */
    public static final int TYPE_NUM_UPPER = 3;

    /**
     * 验证码类型为数字和小写字母混合
     */
    public static final int TYPE_NUM_LOWER = 4;

    /**
     * 验证码类型为仅大写字母
     */
    public static final int TYPE_UPPER_ONLY = 5;

    /**
     * 验证码类型为仅小写字母
     */
    public static final int TYPE_LOWER_ONLY = 6;

    private VerifyCodeUtil() {
    }

    /**
     * 生成随机颜色
     */
    private static Color generateRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }


    /**
     * 生成图片验证码
     *
     * @param type           验证码类型,参见本类的静态属性
     * @param length         验证码字符长度,要求大于0的整数
     * @param excludeString  需排除的特殊字符
     * @param width          图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
     * @param height         图片高度
     * @param interLine      图片中干扰线的条数
     * @param randomLocation 每个字符的高低位置是否随机
     * @param backColor      图片颜色,若为null则表示采用随机颜色
     * @param foreColor      字体颜色,若为null则表示采用随机颜色
     * @param lineColor      干扰线颜色,若为null则表示采用随机颜色
     * @param frameColor     边框颜色,若为null则表示采用黑色
     * @return 图片缓存对象
     */
    public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor, Color frameColor) {
        String textCode = generateCode(type, length, excludeString);
        return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor, frameColor);
    }


    /**
     * 生成验证码字符串
     *
     * @param type          验证码类型,参见本类的静态属性
     * @param length        验证码长度,要求大于0的整数
     * @param excludeString 需排除的特殊字符(无需排除则为null)
     * @return 验证码字符串
     */
    public static String generateCode(int type, int length, String excludeString) {
        if (length <= 0) {
            return "";
        }
        StringBuffer verifyCode = new StringBuffer();
        int i = 0;
        Random random = new Random();
        switch (type) {
            case TYPE_NUM_ONLY:
                while (i < length) {
                    int t = random.nextInt(10);
                    //排除特殊字符
                    if (null == excludeString || excludeString.indexOf(t + "") < 0) {
                        verifyCode.append(t);
                        i++;
                    }
                }
                break;
            case TYPE_LETTER_ONLY:
                while (i < length) {
                    int t = random.nextInt(123);
                    if ((t >= 97 || (t >= 65 && t <= 90)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
            case TYPE_ALL_MIXED:
                while (i < length) {
                    int t = random.nextInt(123);
                    if ((t >= 97 || (t >= 65 && t <= 90) || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
            case TYPE_NUM_UPPER:
                while (i < length) {
                    int t = random.nextInt(91);
                    if ((t >= 65 || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
            case TYPE_NUM_LOWER:
                while (i < length) {
                    int t = random.nextInt(123);
                    if ((t >= 97 || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
            case TYPE_UPPER_ONLY:
                while (i < length) {
                    int t = random.nextInt(91);
                    if ((t >= 65) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
            case TYPE_LOWER_ONLY:
                while (i < length) {
                    int t = random.nextInt(123);
                    if ((t >= 97) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
                        verifyCode.append((char) t);
                        i++;
                    }
                }
                break;
        }
        return verifyCode.toString();
    }

    /**
     * 已有验证码,生成验证码图片
     *
     * @param textCode       文本验证码
     * @param width          图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
     * @param height         图片高度
     * @param interLine      图片中干扰线的条数
     * @param randomLocation 每个字符的高低位置是否随机
     * @param backColor      图片颜色,若为null则表示采用随机颜色
     * @param fontColor      字体颜色,若为null则表示采用随机颜色
     * @param lineColor      干扰线颜色,若为null则表示采用随机颜色
     * @param frameColor     边框颜色,若为null则表示采用黑色
     * @return 图片缓存对象
     */
    public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color fontColor, Color lineColor, Color frameColor) {
        //创建内存图像
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取图形上下文
        Graphics graphics = bufferedImage.getGraphics();
        //画背景图
        graphics.setColor(null == backColor ? generateRandomColor() : backColor);
        graphics.fillRect(0, 0, width, height);
        // 画边框
        graphics.setColor(null == frameColor ? Color.BLACK : frameColor);
        graphics.drawRect(0, 0, width - 1, height - 1);

        //画干扰线
        Random random = new Random();
        if (interLine > 0) {
            int x, y, x1, y1;
            for (int i = 0; i < interLine; i++) {
                graphics.setColor(null == lineColor ? generateRandomColor() : lineColor);
                x = random.nextInt(width);
                y = random.nextInt(height);
                x1 = random.nextInt(width);
                y1 = random.nextInt(height);
                graphics.drawLine(x, y, x1, y1);
            }
        }
        //字体大小为图片高度的80%
        int fsize = (int) (height * 0.8);
        int fx = height - fsize;
        int fy = fsize;
        //设定字体
        graphics.setFont(new Font("Default", Font.PLAIN, fsize));
        //写验证码字符
        for (int i = 0; i < textCode.length(); i++) {
            fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;
            graphics.setColor(null == fontColor ? generateRandomColor() : fontColor);
            //将验证码字符显示到图象中
            graphics.drawString(textCode.charAt(i) + "", fx, fy);
            fx += fsize * 0.9;
        }
        graphics.dispose();
        return bufferedImage;
    }
}
public class BaseController {


    @Resource
    protected HttpServletRequest request;
  

 

    /**
     * 获取Session,没有会自动创建
     *
     * @return
     */
    protected HttpSession getSession() {
        return request.getSession(true);
    }

    /**
     * 设置session的Attribute
     *
     * @param key
     * @param object
     */
    protected void setSessionAttr(String key, Object object) {
        getSession().setAttribute(key, object);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值