springmvc 防止表單重復(fù)提交的兩種方法
最近在本地開(kāi)發(fā)測(cè)試的時(shí)候,遇到一個(gè)表單重復(fù)提交的現(xiàn)象。 因?yàn)榫W(wǎng)絡(luò)延遲的問(wèn)題,我點(diǎn)擊了兩次提交按鈕,數(shù)據(jù)庫(kù)里生成了兩條記錄。其實(shí)這種現(xiàn)象以前也有遇到過(guò),一般都是提交后把按鈕置灰,無(wú)法再次提交,這是很常見(jiàn)的客戶(hù)端處理的方式。 但是這不是從根本上解決問(wèn)題,雖然客戶(hù)端解決了多次提交的問(wèn)題,但是接口中依舊存在著問(wèn)題。假設(shè)我們不是從客戶(hù)端提交,而是被其他的系統(tǒng)調(diào)用,當(dāng)遇到網(wǎng)絡(luò)延遲,系統(tǒng)補(bǔ)償?shù)臅r(shí)候,還會(huì)遇到這種問(wèn)題
1、通過(guò)session中的token驗(yàn)證
- 初始化頁(yè)面時(shí)生成一個(gè)唯一token,將其放在頁(yè)面隱藏域和session中
- 攔截器攔截請(qǐng)求,校驗(yàn)來(lái)自頁(yè)面請(qǐng)求中的token與session中的token是否一致
- 判斷,如果一致則提交成功并移除session中的token,不一致則說(shuō)明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Token { boolean save() default false; boolean remove() default false; }
步驟2:創(chuàng)建自定義攔截器(@slf4j是lombok的注解)
@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:將自定義攔截器添加到配置文件
<mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.chinagdn.base.common.interceptor.RepeatSubmitInterceptor"/> </mvc:interceptor>
使用案例
//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頁(yè)面隱藏域添加token
<input type="hidden" name="token" value="${sessionScope.token}">
2、通過(guò)當(dāng)前用戶(hù)上一次請(qǐng)求的url和參數(shù)驗(yàn)證重復(fù)提交
攔截器攔截請(qǐng)求,將上一次請(qǐng)求的url和參數(shù)和這次的對(duì)比
判斷,是否一致說(shuō)明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SameUrlData { }
步驟2:創(chuàng)建自定義攔截器
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,表示還沒(méi)有訪問(wèn)頁(yè)面 httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams); return false; } else { //否則,已經(jīng)訪問(wèn)過(guò)頁(yè)面 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:將自定義攔截器添加到配置文件
<mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.chinagdn.base.common.interceptor.SameUrlDataInterceptor"/> </mvc:interceptor>
使用案例
//在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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot公共字段填充及ThreadLocal模塊改進(jìn)方案
這篇文章主要為大家介紹了Springboot公共字段填充及ThreadLocal模塊改進(jìn)方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11JavaWeb pageContext對(duì)象原理解析
這篇文章主要介紹了JavaWeb pageContext對(duì)象原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02java 實(shí)現(xiàn)MD5加密算法的簡(jiǎn)單實(shí)例
這篇文章主要介紹了java 實(shí)現(xiàn)MD5加密算法的簡(jiǎn)單實(shí)例的相關(guān)資料,這里提供實(shí)例幫助大家應(yīng)用這樣的加密算法,需要的朋友可以參考下2017-09-09詳解Java函數(shù)式編程和lambda表達(dá)式
這篇文章主要介紹了Java函數(shù)式編程和lambda表達(dá)式,對(duì)lambda感興趣的同學(xué),一定要看一下2021-04-04基于Freemarker和xml實(shí)現(xiàn)Java導(dǎo)出word
這篇文章主要介紹了基于Freemarker和xml實(shí)現(xiàn)Java導(dǎo)出word,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04