注解防止表单重复提交

1. 注解

1
2
3
4
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StopRepeatSubmit {
}

2. 拦截处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @author pibigstar
* @desc 防止表单重复提交拦截处理器
**/

public class StopRepeatSubmitHandlerInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
StopRepeatSubmit annotation = method.getAnnotation(StopRepeatSubmit.class);
if (annotation!=null) {
// 判断是否已经提交过了
String paramter = request.getParameterMap().toString();
String url = request.getRequestURL().toString();
String token = url+paramter;
Object attrToken = request.getSession().getAttribute("token");
if (attrToken == null) {
// 第一次请求
request.getSession().setAttribute("token",token);
return true;
}
if (attrToken.toString().equals(token)){
// 重复提交了
return false;
} else {
// 第一次提交
request.getSession().setAttribute("token",token);
return true;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
}

3. 使用

1
2
3
4
@PostMapping("/submit")
@StopRepeatSubmit
public void submit(){
}
-------------本文结束感谢您的阅读-------------