springboot 项目整合easy-captcha验证码功能

news2024/10/12 10:30:42
效果

1、验证码使用easy-captcha,在pom文件增加依赖
	<!-- google 验证码 -->
		<dependency>
			<groupId>com.github.whvcse</groupId>
			<artifactId>easy-captcha</artifactId>
		</dependency>
2、增加获取kaptcha的ctrl
package com.*.*.system.controller;


import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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


/**
 * @Description
 * @auther zxf
 * @date 29/3/2024 上午 8:49
 */
@RestController
@RequestMapping("kaptcha")
public class KaptchaController {
    @GetMapping("/getKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");

        //生成验证码对象,三个参数分别是宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(100, 38, 4);
        //设置验证码的字符类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        // 设置内置字体
        captcha.setCharType(Captcha.FONT_1);
        //验证码存入session
        httpServletRequest.getSession().setAttribute("kaptcha",captcha.text().toLowerCase());

        //输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }

    public String verify(@RequestParam("code") String code, HttpSession session){
        if (!StringUtils.hasLength(code)){
            return "验证码不能为空";
        }
        String kaptchaCode = session.getAttribute("kaptcha")+"";
        if (!StringUtils.hasLength(kaptchaCode)||!code.toLowerCase().equals(kaptchaCode)){
            return "验证码错误";
        }
        return "验证成功";
    }
}
3、前台
<a-form-item>
	<a-input
	size="large"
	style="width: 80%"
	placeholder="请输入验证码"
	v-decorator="['kaptcha',{rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]" type="text">
	<a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
	</a-input>
	<img alt="验证码" style="float: right" width="65px" height="40px" :src="kaptcha" @click="changekaptcha"/>
</a-form-item>

data里配置:
kaptcha: window.location.origin+"/kaptcha/getKaptcha",

更改验证码方法
changekaptcha(){
			this.kaptcha =this.kaptcha+'?d='+new Date().getTime();
		}

3.增加filter
package com.*.*.*.*.config;

import com.alibaba.fastjson.JSONObject;
import com.gc.common.base.message.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description
 * @auther zxf
 * @date 1/4/2024 下午 3:05
 */
@Slf4j
@Configuration
public class CaptchaFilter implements Filter {
    private static final String CODE_ANT_URL = "auth/login";
    private static final String CAPTCHA_SESSION_KEY = "kaptcha";
    private static final String CAPTCHA_PARAM_NAME = "kaptcha";
    //请求路径匹配
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init()......");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String url = request.getRequestURL().toString();
        //判断请求路径是否是登录路径
        if(!url.contains(CODE_ANT_URL)){
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
                //拿到session中存放的 captcha 属性
                String captcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);
                if (captcha == null) {
                    returnResult(response, "验证码已过期,请重新获取。");
                    return;
            }
                //获取输入的验证码信息
                String inputCaptcha = request.getParameter(CAPTCHA_PARAM_NAME);
                if (inputCaptcha == null || !captcha.equals(inputCaptcha.trim())) {
                    returnResult(response, "验证码错误,请重新输入。");
                    return;
                }
            } else {
            returnResult(response, "无法验证验证码,因为HTTP会话不存在");
            return;
            }
        //判断令牌是否存在,如果不存在则返回错误结果

        filterChain.doFilter(request,response);
    }

    private void returnResult(HttpServletResponse response, String s) throws IOException {
        Result responseResult = Result.failure(s);
        //把Result对象转换为JSON格式字符串
        String json = JSONObject.toJSONString(responseResult);
        response.setContentType("application/json;charset=utf-8");
        //将json字符串返回给页面
        response.getWriter().write(json);
    }

    @Override
    public void destroy() {
        System.out.println("destroy()......");
    }
}

spring security config中设置优先访问filter

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        //增加filter
        http.addFilterBefore(new CaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
        super.configure(http);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1567397.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

pygame三角形重心坐标填充 沿x轴旋转

import pygame from pygame.locals import * import sys import math# 初始化Pygame pygame.init()# 设置窗口大小 width, height 800, 600 screen pygame.display.set_mode((width, height)) pygame.display.set_caption(3D Triangle Fill with Barycentric Coordinates)# 定…

LVS、HAProxy

集群&#xff1a;将很多个机器组织到一起&#xff0c;作为一个整体对外提供服务。集群在扩展性、性能方面都可以做到很灵活。集群的分类&#xff1a;负载均衡集群&#xff1a;Load Balance。高可用集群&#xff1a;High Available。高性能集群&#xff1a;High Performance Com…

MyBatis的基本应用

源码地址 01.MyBatis环境搭建 添加MyBatis的坐标 <!--mybatis坐标--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.9</version></dependency><!--mysql驱动坐…

【大模型】大模型 CPU 推理之 llama.cpp

【大模型】大模型 CPU 推理之 llama.cpp llama.cpp安装llama.cppMemory/Disk RequirementsQuantization测试推理下载模型测试 参考 llama.cpp 描述 The main goal of llama.cpp is to enable LLM inference with minimal setup and state-of-the-art performance on a wide var…

开源模型应用落地-chatglm3-6b模型小试-入门篇(二)

一、前言 刚开始接触AI时&#xff0c;您可能会感到困惑&#xff0c;因为面对众多开源模型的选择&#xff0c;不知道应该选择哪个模型&#xff0c;也不知道如何调用最基本的模型。但是不用担心&#xff0c;我将陪伴您一起逐步入门&#xff0c;解决这些问题。 在信息时代&#xf…

量化交易入门(四十一)ASI指标Python实现和回测

老规矩先上图&#xff0c;看看ASI指标使用苹果数据回测后的结果如何。 一、策略运行结果 执行的结果&#xff1a; Starting Portfolio Value: 100000.00 Final Portfolio Value: 92514.82 Annualized Return: -1.93% Sharpe Ratio: -0.27 Max Drawdown: 25.34% Max Drawdown …

EasyBoss ERP支持TikTok Shop拆单发货功能,多店铺订单包裹拆分一个系统搞定

一些TikTok Shop本土卖家在运营过程中面临这样的困境&#xff1a;当顾客一次性订购多个商品&#xff0c;由于部分商品缺货或包裹超重&#xff0c;订单延迟发货或被物流限制发不出货&#xff0c;导致店铺被投诉。为了解决这一问题&#xff0c;卖家可以采取拆单发货的策略&#x…

C#实现只保存2天的日志文件

文章目录 业务需求代码运行效果 欢迎讨论&#xff01; 业务需求 在生产环境中&#xff0c;控制台窗口不便展示出来。 为了在生产环境中&#xff0c;完整记录控制台应用的输出&#xff0c;选择将其输出到文件中。 但是&#xff0c;存储所有输出的话会占用很多空间&#xff0c;…

Vue项目之路由的高级用法

路由的高级用法 1.路由传参 1.1设置路由&#xff08;在路由中预留参数&#xff09; 组织路由地址的任意位置添加/:参数名&#xff0c;说明要访问这个路径就必须提供这个参数 此例中要想访问资格组件则必须提供对应的3个参数 /参数1/goods/参数2/参数3 注&#xff1a;在路由地…

信息系统项目管理师——第18章项目绩效域管理(一)

本章节内容属于第四版新增知识&#xff0c;为PMBOK第七版专有&#xff0c;选择、案例、论文都会考&#xff0c;属于比较重要的章节。 选择题&#xff0c;稳定考3分左右&#xff0c;新教材基本考课本原话&#xff0c;需要多读课本&#xff0c;多刷题。 案例题&#xff0c;考的概…

【前端Vue】社交信息头条项目完整笔记第3篇:三、个人中心,TabBar 处理【附代码文档】

社交媒体-信息头条项目完整开发笔记完整教程&#xff08;附代码资料&#xff09;主要内容讲述&#xff1a;一、项目初始化使用 Vue CLI 创建项目,加入 Git 版本管理,调整初始目录结构,导入图标素材,引入 Vant 组件库,移动端 REM 适配。二、登录注册准备,实现基本登录功能,登录状…

unity 使用Base64编码工具对xml json 或者其他文本进行加密 解密

Base64编码加密解密工具 这是一个加密解密的网页工具&#xff0c;别人可以把他加密后的字符串给你&#xff0c;然后你可以用代码解密出来&#xff0c; 或者自己对内容进行加密&#xff0c;解密处理。 /// <summary>/// Base64 解码/// </summary>string DecodeBase…

销售与营销的区别:从手中到心中

一、引言 在商界&#xff0c;销售和营销常常被视为同义词&#xff0c;但实际上它们各自扮演着不同的角色。简而言之&#xff0c;销售是将产品送到客户手里&#xff0c;而营销则是将产品送到客户心里。这种微妙的差异对于企业的成功至关重要。正如彼得德鲁克所说&#xff1a;“…

处理SAP报错:消息GLT2076 没有项目种类分配到科目 1481010102/1000

财务新建了个科目入账时报错&#xff1a;没有项目种类分配到科目。 查了下原因。原来是我们公司实施时启用了凭证分割功能。其中有个配置是这样的&#xff1a;给总账科目分类&#xff1a;IMG-财务会计&#xff08;新&#xff09;-总账会计核算-业务交易-凭证分解-为文档拆分给总…

【Java多线程(4)】案例:设计模式

目录 一、什么是设计模式&#xff1f; 二、单例模式 1. 饿汉模式 2. 懒汉模式 懒汉模式-第一次改进 懒汉模式-第二次改进 懒汉模式-第三次改进 一、什么是设计模式&#xff1f; 设计模式是针对软件设计中常见问题的通用解决方案。它们提供了一种被广泛接受的方法来解决…

usbserial驱动流程解析_Part1_主要函数

本系列解析usbseiral ko的源码&#xff0c;记录主要函数&#xff0c;调用流程&#xff0c;USB一端和串口一端的注册流程&#xff0c;本节简介主要函数以及替换规则。 首先&#xff0c;usbserial是USB转串口驱动的一个基础模板&#xff0c;其中有许多默认函数&#xff0c;他们的…

企业管理新思考:利润率与质量在创业路上的重要性

一、引言 在当下这个充满变革与挑战的商业环境中&#xff0c;创业者和企业家们时常面临着规模扩张与利润增长之间的权衡。著名天使投资人吴世春先生的一席话&#xff0c;为我们指明了方向&#xff1a;“做企业利润率优先于规模&#xff0c;质量优先于数量。”这一深刻见解&…

Apache DolphinScheduler 【安装部署】

前言 今天来学习一下 DolphinScheduler &#xff0c;这是一个任务调度工具&#xff0c;现在用的比较火爆。 1、安装部署 1.0、准备工作 1.0.1、集群规划 dolphinscheduler 比较吃内存&#xff0c;所以尽量给 master 节点多分配一点内存&#xff0c;桌面和虚拟机里能关的应用…

Qt C++ | Qt 元对象系统、信号和槽及事件(第一集)

01 元对象系统 一、元对象系统基本概念 1、Qt 的元对象系统提供的功能有:对象间通信的信号和槽机制、运行时类型信息和动态属性系统等。 2、元对象系统是 Qt 对原有的 C++进行的一些扩展,主要是为实现信号和槽机制而引入的, 信号和槽机制是 Qt 的核心特征。 3、要使用元…

JRT简化开发环境

JRT是完全前后端分离的项目&#xff0c;实际工程是逻辑上完全前后端分离&#xff0c;代码层级和工程是不离的。这样就可以做到一键启动&#xff0c;同时又有分离的好处。开始页面后缀都沿用aspx&#xff0c;最开始考虑过修改后缀为html&#xff0c;当时觉得搞aspx也不错&#x…