springBoot防止重复提交

两种方法,
一种是后端实现,较复杂,要通过自定义注解和AOP以及Redis组合实现
另一种是前端实现,简单,只需通过js,设置过期时间,一定时间内,多次点击按钮只生效一次

后端实现

自定义注解+AOP+Redis

自定义注解

package com.wzw.config.anno;import java.lang.annotation.*;/*** 自定义注解防止表单重复提交*/
@Target(ElementType.METHOD) // 注解只能用于方法
@Retention(RetentionPolicy.RUNTIME) // 修饰注解的生命周期
@Documented
public @interface RepeatSubmit {/*** 防重复操作过期时间,默认1s*/long expireTime() default 1;
}

AOP

package com.wzw.config.aspect;import com.wzw.config.anno.RepeatSubmit;
import com.wzw.config.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;/*** 防止重复提交切面*/
@Slf4j
@Component
@Aspect
public class RepeatSubmitAspect {@Autowiredprivate RedisTemplate redisTemplate;/*** 定义切点*/@Pointcut("@annotation(com.wzw.config.anno.RepeatSubmit)")public void repeatSubmit() {}@Around("repeatSubmit()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();// 获取防重复提交注解RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);// 获取token当做keyString token = request.getHeader("token");if (StringUtils.isBlank(token)) {throw new RuntimeException("token不存在,请登录!");}String url = request.getRequestURI();/***  通过前缀 + url + token 来生成redis上的 key*  可以在加上用户id,小编这里没办法获取,大家可以在项目中加上*/String redisKey = "repeat_submit_key:".concat(url).concat(token);log.info("==========redisKey ====== {}",redisKey);if (!redisTemplate.hasKey(redisKey)) {redisTemplate.opsForValue().set(redisKey, redisKey, annotation.expireTime(), TimeUnit.SECONDS);try {//正常执行方法并返回return joinPoint.proceed();} catch (Throwable throwable) {redisTemplate.delete(redisKey);throw new Throwable(throwable);}} else {// 抛出异常throw new CustomException("请勿重复提交");}}
}

自定义异常类和全局异常处理

自定义异常类:CustomException

package com.wzw.config.exception;/*** 自定义异常*/
public class CustomException extends Exception {public CustomException() {super();}public CustomException(String message) {super(message);}
}

全局异常处理:CustomExceptionHandler

package com.wzw.config.exception;import com.wzw.base.pojo.Result;
import com.wzw.config.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {/*** 每当抛出CustomException异常,就会进入这里* @param e 自定义异常类* @return  返回值实体*/@ExceptionHandler(value = CustomException.class)@ResponseBodypublic Result handleCustomException(CustomException e){Result result=Result.init();result.setMsg(e.getMessage());result.setCode(0);return result;}}

响应实体:Result

package com.wzw.base.pojo;import lombok.Data;/*** 返回值响应实体*/
@Data
public class Result {private int code;private String msg;private Object data;public static Result init(){return new Result();}public static Result ok(){Result result=Result.init();result.code=1;return result;}public static Result ok(String msg){Result result=Result.ok();result.setMsg(msg);return result;}public static Result err(){Result result=Result.init();result.code=0;return result;}public static Result err(String msg){Result result=Result.err();result.setMsg(msg);return result;}
}

Redis

设置Redis配置数据源,然后创建 Redis配置类

package com.wzw.config.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);// Hash的key也采用StringRedisSerializer的序列化方式template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);template.afterPropertiesSet();return template;}
}

使用

    /*** 防止重复提交测试* @return  响应实体* @throws CustomException  自定义异常类*/@RequestMapping("/testCustomerException")@ResponseBody@RepeatSubmit(expireTime = 10)  //不加expireTime,默认1s内,加参数可以重新设定防止重复提交的时间public Result testCustomerException() throws CustomException {Result result=Result.ok("请求成功");return result;}

可以看到第一次是请求成功,之后五秒都是提示请勿重复提交
在这里插入图片描述

前端实现

来源:https://blog.csdn.net/liangmengbk/article/details/127075604

/* 防止重复点击 */
let clickTimer = 0function clickThrottle() {var interval = 3000;//3秒钟之内重复点击只算一次点击let now = +new Date(); // 获取当前时间的时间戳let timer = clickTimer; // 记录触发事件的事件戳if (now - timer < interval) {// 如果当前时间 - 触发事件时的事件 < interVal,那么不符合条件,直接return false,// 不让当前事件继续执行下去return false;} else {// 反之,记录符合条件触发了事件的时间戳,并 return true,使事件继续往下执行clickTimer = now;return true;}
}

在需要的地方进行调用:

if(!clickThrottle()) return;

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

回归预测 | MATLAB实现SSA-RF麻雀搜索优化算法优化随机森林算法多输入单输出回归预测(多指标,多图)

回归预测 | MATLAB实现SSA-RF麻雀搜索优化算法优化随机森林算法多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09; 目录 回归预测 | MATLAB实现SSA-RF麻雀搜索优化算法优化随机森林算法多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09;…

JAVA结合AE(Adobe After Effects)AE模板文件解析生成视频实现类似于逗拍(视频DIY)的核心功能

最近看抖音上有很多各种视频表白生成的直播而且直播间人很多&#xff0c;于是就思考如何实现的视频内的文字图片内容替换的呢 &#xff0c;答案需要用到类似与逗拍一样的视频DIY的功能&#xff0c;苦于我是java&#xff0c;百度了半天没有办法和思路&#xff0c;总不能为了一个…

[oneAPI] 基于BERT预训练模型的英文文本蕴含任务

[oneAPI] 基于BERT预训练模型的英文文本蕴含任务 Intel DevCloud for oneAPI 和 Intel Optimization for PyTorch基于BERT预训练模型的英文文本蕴含任务语料介绍数据集构建 模型训练 结果参考资料 比赛&#xff1a;https://marketing.csdn.net/p/f3e44fbfe46c465f4d9d6c23e38e0…

PIL.Image和base64,格式互转

将PIL.Image转base64 ##PIL转base64 import base64 from io import BytesIOdef pil_base64(image):img_buffer BytesIO()image.save(img_buffer, formatJPEG)byte_data img_buffer.getvalue()base64_str base64.b64encode(byte_data)return base64_str将base64转PIL.Image …

公司核心文件数据防泄密系统——「天锐绿盾加密软件」

企业内每日的文档传输可能会发生成千上万次以上&#xff0c;已经成为最容易泄密的环节。在日常工作中&#xff0c;我们无法避免通过即时通讯工具、网络、邮件、移动设备等方式传输机密文档&#xff0c;那么我们该如何保障文档传输安全呢&#xff1f;为此天锐绿盾终端管理系统提…

FL Studio21.1中文完整版Win/Mac

FL Studio All Plugins Edition【中文完整版 Win/Mac】适合音乐制作人/工作室使用&#xff0c;全套插件!&#xff08;20.9新增Vintage Chorus&#xff0c;Pitch Shifter变调插件&#xff09;FL Studio是超多顶级音乐人的启蒙首选&#xff01;包括百大DJ冠军Martin Garrix&…

【面试】项目经理面试题

文章目录 一、项目管理面试中通常会问到的问题1.项目管理软件工具知识2.做项目计划的技能3.人员管理技能4.沟通技巧5.方法论知识 二、问面试官的问题三. 面试系列推荐 一、项目管理面试中通常会问到的问题 1.项目管理软件工具知识 问题 1: 工期和工作量之间的差异是什么? 答案…

jenkins使用

安装插件 maven publish over ssh publish over ssh 会将打包后的jar包&#xff0c;通过ssh推送到指定的服务器上&#xff0c;&#xff0c;在jenkins中设置&#xff0c;推送后脚本&#xff0c;实现自动部署jar包&#xff0c;&#xff0c; 装了这个插件之后&#xff0c;可以在项…

ssm+vue绿色农产品推广应用网站源码和论文PPT

ssmvue绿色农产品推广应用网站041 开发工具&#xff1a;idea 数据库mysql5.7 数据库链接工具&#xff1a;navcat,小海豚等 技术&#xff1a;ssm 摘 要 21世纪的今天&#xff0c;随着社会的不断发展与进步&#xff0c;人们对于信息科学化的认识&#xff0c;已由低层次向高…

【仿写tomcat】六、解析xml文件配置端口、线程池核心参数

线程池改造 上一篇文章中我们用了Excutors创建了线程&#xff0c;这里我们将它改造成包含所有线程池核心参数的形式。 package com.tomcatServer.http;import java.util.concurrent.*;/*** 线程池跑龙套** author ez4sterben* date 2023/08/05*/ public class ThreadPool {pr…

Android企业项目开发实训室建设方案

一 、系统概述 Android企业项目开发作为新一代信息技术的重点和促进信息消费的核心产业&#xff0c;已成为我国转变信息服务业的发展新热点&#xff1a;成为信息通信领域发展最快、市场潜力最大的业务领域。互联网尤其是移动互联网&#xff0c;以其巨大的信息交换能力和快速渗透…

科技政策 | 四川省科学技术厅关于发布2024年第一批省级科技计划项目申报指南的通知

原创 | 文 BFT机器人 近日&#xff0c;四川省科学技术厅发布了2024年第一批省级科技计划项目申报指南&#xff1b;其中包括自然科学基金项目、重点研发计划、科技成果转移转化引导计划、科技创新基地&#xff08;平台&#xff09;和人才计划。 01 自然科学基金项目 实施周期 …