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);
}
}