springboot防止表单重复提交

最近负责一个后台框架的搭建,使用的是springboot redis jwt 一直哐哐写,没有想到表单重复提交的问题,晚上想结构的时候突然想起来。
上代码,
引入依赖;
使用aop做拦截

   <!-- SpringBoot 拦截器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
	
        <!-- SpringBoot 集成redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

自定义注解

@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit {
}

编写拦截

@Aspect
@Component
public class NoRepeatSubmitAop {

    private static final Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAop.class);

    @Autowired
    private RedisUtil redisUtil;
	// 这个看自己的包结构 不然不做拦截
    @Around("execution(* com.jianfan.mdt.backend.project..*Controller.*(..))&& @annotation(nos)") 
    public Object arround(ProceedingJoinPoint pjp, RepeatSubmit nos) { //RepeatSubmit自己的写注解的名字

        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            HttpServletRequest request = attributes.getRequest();
            String key = sessionId + "-" + request.getServletPath();
            if(redisUtil.get(key)==null){
                Object o = pjp.proceed();
               redisUtil.set(key,key,5);//设置5秒内不能重复提交
                return o;
            } else {
                logger.error("重复提交");
                return BaseResult.build(StatusCode.SERVICEERROR,StatusCode.REPAATMSG);
            }

        } catch (Throwable throwable) {
            logger.error("验证重复提交时出现未知异常!");
            return BaseResult.build(StatusCode.SERVICEERROR,StatusCode.REPAATMSGEXCEPT);
        }

    }

}

注解使用
在这里插入图片描述
测试结果
在这里插入图片描述
点赞加关注;免费分享众多开源项目;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值