spring_注解与拦截器的结合(防止重复提交)

1.创建注解:

/**
 * @author xuliduo
 * @date 2018/12/19
 * @description class RepeatedCheck
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatedCheck {
    /**
     * 是否开启 验证
     *
     * @return check 默认为 true
     */
    boolean check() default true;

    /**
     * 验证check 间隔时间 单位为妙
     *
     * @return time 默认为 3
     */
    int time() default 3;
}
/**
 * @author xuliduo
 * @date 2018/12/19
 * @description 通用防重复提交拦截器
 */
public class RepeatedInterceptor extends HandlerInterceptorAdapter {
    private final static String key = "REPEATED_";
    private StringRedisTemplate stringRedisTemplate;

    public RepeatedInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatedCheck annotation = method.getAnnotation(RepeatedCheck.class);
            if (annotation != null && annotation.check()) {
                System.out.println("重复提交注解");
                int hash = Objects.hash(request.getRequestURI(), request.getMethod());
                if (stringRedisTemplate.opsForValue().get(key + hash) != null) {
                    throw  new Exception("请勿重复提交");
                } else {
                    stringRedisTemplate.opsForValue().set(key + hash, "1", annotation.time(), TimeUnit.SECONDS);
                }
            }else{
                System.out.println("没有重复提交注解");
            }
        }
        return super.preHandle(request, response, handler);
    }
**
 * Auther: ruoyu
 * Date: 19-2-18
 * Description: 新增自定义拦截器到拦截器链中
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //注册自定义拦截器到 拦截器链中
//        registry.addInterceptor(new MyTestInterceptor("测试")).addPathPatterns("/**");
        registry.addInterceptor(new RepeatedInterceptor(stringRedisTemplate)).addPathPatterns("/**");
        super.addInterceptors(registry);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值