springboot2.1+redis+拦截器防止表单重复提交详细介绍

本文介绍了如何在SpringBoot2.1项目中利用Redis和自定义拦截器实现表单重复提交的防护。通过创建`AutoIdempotent`注解、拦截器注册及控制器方法上的注解应用,配合Token生成工具类`TokenService`和Redis工具类`RedisUtil`,有效防止了表单的重复提交。如需完整代码,可前往CSDN下载。
摘要由CSDN通过智能技术生成

创建AutoIdempotent 拦截注解,后面使用在方法直接注解即可

@Target(ElementType.METHOD) //应用在方法级别上
@Retention(RetentionPolicy.RUNTIME)//运行时
public @interface AutoIdempotent {
   

}

创建拦截器

public class AutoIdempotentInterceptor implements HandlerInterceptor{
   

    @Autowired
    private TokenServiceImpl tokenService; //token生成类

    /**
     * 预处理 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   
        if (!(handler instanceof HandlerMethod)) {
   
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //被ApiIdempotment标记的扫描
        AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
        if (methodAnnotation != null) {
   
            try {
   
              return tokenService.checkToken(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
            }catch (Exception ex){
   
                response.setContentType("text/html;charset=UTF-8");
                Map<String,Object&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值