八、SpringMVC环境下验证码的使用

9 篇文章 1 订阅

RandomValidateCode.java,生成二维码的核心代码

package main.java.com.smart.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

@Component
public class RandomValidateCode {

    /**
     * 1)生成代码
     * 
     * @return
     */
    public static String createValidateCode(int size) {
        String seed = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        int len = seed.length();
        char[] p = new char[size];//定义随机代码的长度
        for(int i = 0; i < size; i++){
            p[i] = seed.charAt((int)Math.floor(Math.random() * len));
        }
        return new String(p);
    }

    private final Random random = new Random();

    private final String randString = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";// 随机产生的字符串
    private final int width = 135;//图片宽
    private final int height = 40;//图片高
    private final int lineSize = 50;//干扰线数量
    private final int stringNum = 4;//随机产生字符数量

    private final int fontSize = 30;//

    /**
     * 生成随机图片
     */
    public void getRandcode(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        // 1、BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_BGR);
        // 2、产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, this.width, this.height);
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, this.fontSize));
        g.setColor(this.getRandColor(110, 133));//随机颜色
        // 3、绘制干扰线
        for (int i = 0; i <= this.lineSize; i++) {
            this.drawLine(g);
        }
        // 4、绘制随机字符
        String randomString = "";
        for (int i = 1; i <= this.stringNum; i++) {
            randomString = this.drawString(g, randomString, i);
        }
        session.removeAttribute(Constants.RANDOM_CODE_KEY);//5、移除原本的属性值
        session.setAttribute(Constants.RANDOM_CODE_KEY, randomString);//6、添加新的属性值
        // System.out.println(randomString);
        g.dispose();//7、手动销毁图形对象,以免占用系统资源
        try {
            // 8、禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            // 9、将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取随机的字符
     */
    public String getRandomString(int num) {
        return String.valueOf(this.randString.charAt(num));
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(Graphics g) {
        int x = this.random.nextInt(this.width);
        int y = this.random.nextInt(this.height);
        int xl = this.random.nextInt(13);
        int yl = this.random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }

    /**
     * 绘制字符串
     */
    private String drawString(Graphics g, String randomString, int i) {
        g.setFont(this.getFont());
        g.setColor(new Color(this.random.nextInt(155), this.random.nextInt(123), this.random.nextInt(176)));
        String rand = String.valueOf(this.getRandomString(this.random.nextInt(this.randString.length())));
        randomString += rand;
        g.translate(this.random.nextInt(3), this.random.nextInt(3));
        g.drawString(rand, (this.width / this.stringNum - 14) * i, this.height - 7);
        return randomString;
    }

    /**
     * 获得字体
     */
    private Font getFont() {
        return new Font("Times New Roman", Font.CENTER_BASELINE, this.fontSize);
    }

    /**
     * 获得颜色
     */
    private Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + this.random.nextInt(bc - fc - 16);
        int g = fc + this.random.nextInt(bc - fc - 14);
        int b = fc + this.random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }
}

ToolController.java

package main.java.com.smart.web;

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

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

import main.java.com.smart.common.RandomValidateCode;

@Controller
public class ToolController {

    @Resource
    RandomValidateCode code;

    /**
     * 向服务器请求一个验证码
     * 
     * @param request
     * @param response
     */
    @RequestMapping("/vcode")
    public void vcode(HttpServletRequest request, HttpServletResponse response){
        code.getRandcode(request, response);
    }
}

ulogin.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>登录用户桌面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/public.css" type="text/css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/allprivate.css" type="text/css">
</head>
<body>
    <script type="text/javascript">
        var i = 1;
        function changecode(){
            document.getElementById('vcode').src="vcode.html?v=" + (i++);
        }
    </script>
    <div id="container">
        <div class="ulogin">
            <p class="ulogin_head"><span>用户登录</span></p>
            <form class="ulogin_form" onsubmit="return checkUserName()" method="POST" action="user/doLogin.html">
                <table>
                    <tr>
                        <td>账号</td>
                        <td><input type="text" name="uid" id="uid" class="ulogin_form_1" 
                        required v-model="uid_text" :placeholder="tip_uid" :maxlength="userlength"></td>
                    </tr>
                    <tr>
                        <td>密码</td>
                        <td><input type="password" name="password" id="pwd" class="ulogin_form_1" 
                        required v-model="pwd_text" :placeholder="tip_pwd" :maxlength="pwdlength"></td>
                    </tr>
                    <tr>
                        <td><input type="text" name="vcode"></td>
                        <td><input id="vcode" type="image" src="vcode.html" onclick="changecode()"></td>
                    </tr>
                </table>
                <p class="ulogin_form_line"></p>
                <input type="submit" name="登录" class="ulogin_form_2">
                <input type="reset" name="重置" class="ulogin_form_2">
            </form>
        </div>
        <div><a href="user/register.html">用户注册</a></div>
        <font color="red">${verror}</font>
        <font color="red">${error}</font>
    </div>
    <script src="${pageContext.request.contextPath}/static/js/vue.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/login.js"></script>
</body>
</html>

最后通过对比用户输入的和服务器保存的验证码,判断用户是否正确输入验证码
String sessionCode = (String)request.getSession().getAttribute(Constants.RANDOM_CODE_KEY);


原创+转载,如有侵权请指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值