javaWeb 、Springboot 生成验证码

24 篇文章 0 订阅
9 篇文章 0 订阅

自定义生成验证码类:

package com.file.utlis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author 19417
 */
@RestController
public class SecurityCodeUtil {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    // 常用字符集
    private char[] data = "ZXCVBNMASDFGHJKLPOIUYTREWQabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
    //随机验证码胡Session中的名称
    private String code = "";

    public static final int WIDTH = 120;
    public static final int HEIGHT = 30;


    @GetMapping("/verifCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);// 创建缓存

        Graphics graphics = image.getGraphics();// 获得画布
        setBackGround(graphics);// 设置背影色
        setBorder(graphics);// 设置边框
        drawRandomLine(graphics);// 画干扰线
        String random = drawRandomNum((Graphics2D) graphics);// 写随机数

        //核心代码:将随机字符存在redis中 单体项目放在 session中即可
        redisTemplate.opsForValue().set("verifCode", random);

        response.setContentType("image/jpeg");// 将图形写给浏览器
        // 发头控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        ImageIO.write(image, "jpg", response.getOutputStream());// 将图片写给浏览器
    }

    // 设置背景色
    private void setBackGround(Graphics g) {
        g.setColor(Color.WHITE);// 设置颜色
        g.fillRect(0, 0, WIDTH, HEIGHT);// 填充区域

    }


    //设置边框
    private void setBorder(Graphics g) {
        g.setColor(Color.BLUE);// 设置边框颜色
        g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);// 边框区域
    }


    // 画随机线条
    private void drawRandomLine(Graphics g) {
        g.setColor(Color.GREEN);// 设置颜色
        for (int i = 0; i < 5; i++) {// 设置线条个数并画线
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
    }


    // 画随机汉字
    private String drawRandomNum(Graphics2D g) {
        StringBuffer sb = new StringBuffer();

        g.setColor(Color.RED);// 设置颜色

        g.setFont(new Font("宋体", Font.BOLD, 24));// 设置字体
        int x = 5;// 控制字数

        for (int i = 0; i < 4; i++) {
            int degree = new Random().nextInt() % 30;// 设置字体旋转角度

            String ch = data[new Random().nextInt(data.length)] + "";// 截取汉字
            sb.append(ch);

            g.rotate(degree * Math.PI / 180, x, 20);// 正向角度
            g.drawString(ch, x, 20);
            // 反向角度
            g.rotate(-degree * Math.PI / 180, x, 20);
            x += 30;
        }
        return sb.toString();
    }



     //用于比对用户输入的验证码是否正确 逻辑自己定义即可
    @PostMapping("/checkCode")
    public boolean checkCode(HttpServletRequest request) {
        String code = request.getParameter("code");

        return true;

    }
}

登陆页面:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>后台管理-登陆</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="lib/layui-v2.5.5/css/layui.css" media="all">
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        html, body {
            width: 100%;
            height: 100%;
            overflow: hidden
        }

        body {
            background: #1E9FFF;
        }

        body:after {
            content: '';
            background-repeat: no-repeat;
            background-size: cover;
            -webkit-filter: blur(3px);
            -moz-filter: blur(3px);
            -o-filter: blur(3px);
            -ms-filter: blur(3px);
            filter: blur(3px);
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: -1;
        }

        .layui-container {
            width: 100%;
            height: 100%;
            overflow: hidden
        }

        .admin-login-background {
            width: 360px;
            height: 300px;
            position: absolute;
            left: 50%;
            top: 40%;
            margin-left: -180px;
            margin-top: -100px;
        }

        .logo-title {
            text-align: center;
            letter-spacing: 2px;
            padding: 14px 0;
        }

        .logo-title h1 {
            color: #1E9FFF;
            font-size: 25px;
            font-weight: bold;
        }

        .login-form {
            background-color: #fff;
            border: 1px solid #fff;
            border-radius: 3px;
            padding: 14px 20px;
            box-shadow: 0 0 8px #eeeeee;
        }

        .login-form .layui-form-item {
            position: relative;
        }

        .login-form .layui-form-item label {
            position: absolute;
            left: 1px;
            top: 1px;
            width: 38px;
            line-height: 36px;
            text-align: center;
            color: #d2d2d2;
        }

        .login-form .layui-form-item input {
            padding-left: 36px;
        }

        .captcha {
            width: 60%;
            display: inline-block;
        }

        .captcha-img {
            display: inline-block;
            width: 34%;
            float: right;
        }

        .captcha-img img {
            height: 34px;
            border: 1px solid #e6e6e6;
            height: 36px;
            width: 100%;
        }
    </style>
</head>
<body>
<div class="layui-container">
    <div class="admin-login-background">
        <div class="layui-form login-form">
            <form class="layui-form" action="">
                <div class="layui-form-item logo-title">
                    <h1>LayuiMini后台登录</h1>
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-username" for="username"></label>
                    <input type="text" name="username" lay-verify="required|account" placeholder="用户名或者邮箱"
                           autocomplete="off" class="layui-input" value="root">
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-password" for="password"></label>
                    <input type="password" name="password" lay-verify="required|password" placeholder="密码"
                           autocomplete="off" class="layui-input" value="root">
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-vercode" for="captcha"></label>
                    <input type="text" name="captcha" id="codeInput" lay-verify="required|captcha" placeholder="图形验证码"
                           autocomplete="off" class="layui-input verification captcha"  value="xszg">
                    <span id="tip"></span>
                    <div class="captcha-img">
                        <img id="captchaPic"  src="http://localhost:8080/verifCode"  alt="验证码获取时 端口号错误"   >
                    </div>
                </div>
                <div class="layui-form-item">
                    <input type="checkbox" name="rememberMe" value="true" lay-skin="primary" title="记住密码">
                </div>
                <div class="layui-form-item">
                    <button  type="submit" class="layui-btn layui-btn layui-btn-normal layui-btn-fluid" lay-submit="login"
                            lay-filter="login">登 入
                    </button>
                    <br>
                    <br>
                    <button type="reset" class="layui-btn layui-btn layui-btn-normal layui-btn-fluid">重置</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="js/glubo.js" charset="utf-8"></script>
<script src="lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>



<script>
    layui.use(['table', 'form', 'jquery', 'layer'], function () {
        var table = layui.table,
            form = layui.form,
            $ = layui.jquery,
            layer = layui.layer;

        // 登录过期的时候,跳出ifram框架
        if (top.location != self.location) top.location = self.location;

        // 粒子线条背景
        $(document).ready(function () {
            $('.layui-container').particleground({
                dotColor: '#7ec7fd',
                lineColor: '#7ec7fd'
            });
        });

        // 进行登录操作
        form.on('submit(login)', function (data) {
            data = data.field;
            if (data.username == '') {
                layer.msg('用户名不能为空');
                return false;
            }
            if (data.password == '') {
                layer.msg('密码不能为空');
                return false;
            }
            if (data.captcha == '') {
                layer.msg('验证码不能为空');
                return false;
            }


            $.post(httpurl + "/login", {
                'username':  data.username,
                'password': data.password
            }, function (res) {
                if (res) {
                    layer.msg('登录成功', {icon: 6}, function () {
                        window.location = 'index.html';
                    });
                } else {
                    layer.msg('登录失败', {icon: 5}, function () {
                        window.location = 'login.html';
                    });
                }
            });


            return false;
        });


 //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
        $("#captchaPic").click(function (res) {
            var url = httpurl + "/verifCode";
            var imgSrc = $("#captchaPic");
            url = $("#captchaPic").attr("src");
            imgSrc.attr("src", function () {
                var timestamp = (new Date()).valueOf();
                url = url + "?timestamp=" + timestamp;
                return url;
            });
        });



        $("#codeInput").blur(function (res) {
            var code = $("#codeInput").val();

            $.post(httpurl+"/checkCode",{'code': code},function (res) {
               if(res){
                   layer.msg('验证码正确', {icon: 6});
               }else {
                   layer.msg('验证码失败', {icon: 5});
               }
            });
        });



    });
</script>
</body>
</html>

效果图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缘不易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值