Springboot+thymeleaf实现验证码

验证码使用了Hutool工具类实现
导入Hutool工具类依赖

		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.8</version>
        </dependency>

在controller上写上获取验证码的接口

private LineCaptcha lineCaptcha;
 /**获取验证码*/
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(110, 36);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法,设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

在html页面进行接口调用/getCode

<div class="form-group row mt-4">
	<label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label>
		<div class="col-sm-7">
			<input type="text" th:class="|form-control ${codeMsg!=null?'is-invalid':''}|" id="verifycode" name="code" placeholder="请输入验证码!">
				<div class="invalid-feedback" th:text="${codeMsg}">
					验证码不正确!
				</div>
		</div>
		<div class="col-sm-2">
		<img src="/getCode" id="captchaPic" style="width:100px;height:40px;" class="mr-2" onclick="refresh()"/>
		</div>
</div>	

点击图片刷新验证码事件,使用js编写refresh()方法

<script>
		function refresh() {
			document.getElementById("captchaPic").src = "getCode?time=" + new Date().getTime();
		}
</script>

检验验证码,在登录接口进行代码添加

// 检查验证码,前端床来的code使用String接收
        String kaptcha =lineCaptcha.getCode();
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确!");
            return "/site/login";//返回登录页面
        }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蒙面侠1024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值