最近在本地開發(fā)測試的時(shí)候,遇到一個(gè)表單重復(fù)提交的現(xiàn)象。 因?yàn)榫W(wǎng)絡(luò)延遲的問題,我點(diǎn)擊了兩次提交按鈕,數(shù)據(jù)庫里生成了兩條記錄。其實(shí)這種現(xiàn)象以前也有遇到過,一般都是提交后把按鈕置灰,無法再次提交,這是很常見的客戶端處理的方式。 但是這不是從根本上解決問題,雖然客戶端解決了多次提交的問題,但是接口中依舊存在著問題。假設(shè)我們不是從客戶端提交,而是被其他的系統(tǒng)調(diào)用,當(dāng)遇到網(wǎng)絡(luò)延遲,系統(tǒng)補(bǔ)償?shù)臅r(shí)候,還會(huì)遇到這種問題
1、通過session中的token驗(yàn)證
- 初始化頁面時(shí)生成一個(gè)唯一token,將其放在頁面隱藏域和session中
- 攔截器攔截請求,校驗(yàn)來自頁面請求中的token與session中的token是否一致
- 判斷,如果一致則提交成功并移除session中的token,不一致則說明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
1
2
3
4
5
6
|
@Target (ElementType.METHOD) @Retention (RetentionPolicy.RUNTIME) public @interface Token { boolean save() default false ; boolean remove() default false ; } |
步驟2:創(chuàng)建自定義攔截器(@slf4j是lombok的注解)
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
41
42
43
44
45
46
47
48
49
50
|
@Slf4j public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod handlerMethod = null ; try { handlerMethod = (HandlerMethod)handler; } catch (Exception e) { return true ; } Method method = handlerMethod.getMethod(); Token token = method.getAnnotation(Token. class ); if (token != null ){ boolean saveSession = token.save(); if (saveSession){ request.getSession( true ).setAttribute( "token" , UUID.randomUUID()); } boolean removeSession = token.remove(); if (removeSession){ if (isRepeatSubmitSession(request)){ log.info( "repeat submit session :" + request.getServletPath()); response.sendRedirect( "/error/409" ); return false ; } request.getSession( true ).removeAttribute( "token" ); } } return true ; } private boolean isRepeatSubmitSession(HttpServletRequest request){ String sessionToken = String.valueOf(request.getSession( true ).getAttribute( "token" ) == null ? "" : request.getSession( true ).getAttribute( "token" )); String clientToken = String.valueOf(request.getParameter( "token" ) == null ? "" : request.getParameter( "token" )); if (sessionToken == null || sessionToken.equals( "" )){ return true ; } if (clientToken == null || clientToken.equals( "" )){ return true ; } if (!sessionToken.equals(clientToken)){ return true ; } return false ; } } |
步驟3:將自定義攔截器添加到配置文件
1
2
3
4
|
< mvc:interceptor > < mvc:mapping path = "/**" /> < bean class = "com.chinagdn.base.common.interceptor.RepeatSubmitInterceptor" /> </ mvc:interceptor > |
使用案例
1
2
3
4
5
6
7
8
9
10
11
12
|
//save = true 用于生成token @Token (save = true ) @RequestMapping (value = "save" , method = RequestMethod.GET) public String save(LoginUser loginUser, Model model) throws Exception { return "sys/user/edit" ; } //remove = true 用于驗(yàn)證token @Token (remove = true ) @RequestMapping (value = "save" , method = RequestMethod.POST) public String save( @Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception { //..... } |
jsp頁面隱藏域添加token
1
|
<input type= "hidden" name= "token" value= "${sessionScope.token}" > |
2、通過當(dāng)前用戶上一次請求的url和參數(shù)驗(yàn)證重復(fù)提交
攔截器攔截請求,將上一次請求的url和參數(shù)和這次的對(duì)比
判斷,是否一致說明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
1
2
3
4
5
|
@Target (ElementType.METHOD) @Retention (RetentionPolicy.RUNTIME) public @interface SameUrlData { } |
步驟2:創(chuàng)建自定義攔截器
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
41
42
43
44
45
46
47
48
49
|
public class SameUrlDataInterceptor 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(); //是否有 SameUrlData 注解 SameUrlData annotation = method.getAnnotation(SameUrlData. class ); if (annotation != null ) { if (repeatDataValidator(request)) { //如果重復(fù)相同數(shù)據(jù) response.sendRedirect( "/error/409" ); return false ; } else { return true ; } } return true ; } else { return super .preHandle(request, response, handler); } } /** * 驗(yàn)證同一個(gè)url數(shù)據(jù)是否相同提交 ,相同返回true * @param httpServletRequest * @return */ private boolean repeatDataValidator(HttpServletRequest httpServletRequest) { String params = JsonMapper.toJsonString(httpServletRequest.getParameterMap()); String url = httpServletRequest.getRequestURI(); Map<String, String> map = new HashMap<>(); map.put(url, params); String nowUrlParams = map.toString(); // Object preUrlParams = httpServletRequest.getSession().getAttribute( "repeatData" ); if (preUrlParams == null ) { //如果上一個(gè)數(shù)據(jù)為null,表示還沒有訪問頁面 httpServletRequest.getSession().setAttribute( "repeatData" , nowUrlParams); return false ; } else { //否則,已經(jīng)訪問過頁面 if (preUrlParams.toString().equals(nowUrlParams)) { //如果上次url+數(shù)據(jù)和本次url+數(shù)據(jù)相同,則表示城府添加數(shù)據(jù) return true ; } else { //如果上次 url+數(shù)據(jù) 和本次url加數(shù)據(jù)不同,則不是重復(fù)提交 httpServletRequest.getSession().setAttribute( "repeatData" , nowUrlParams); return false ; } } } } |
步驟3:將自定義攔截器添加到配置文件
1
2
3
4
|
< mvc:interceptor > < mvc:mapping path = "/**" /> < bean class = "com.chinagdn.base.common.interceptor.SameUrlDataInterceptor" /> </ mvc:interceptor > |
使用案例
1
2
3
4
5
6
|
//在controller層使用 @SameUrlData 注解即可 @SameUrlData @RequestMapping (value = "save" , method = RequestMethod.POST) public String save( @Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception { //..... } |
到此這篇關(guān)于springmvc 防止表單重復(fù)提交的兩種方法的文章就介紹到這了,更多相關(guān)springmvc 防止表單重復(fù)提交內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://juejin.cn/post/6990963223486791688