您好,登錄后才能下訂單哦!
這篇文章給大家介紹springmvc中如何防止表單重復提交,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
初始化頁面時生成一個唯一token,將其放在頁面隱藏域和session中
攔截器攔截請求,校驗來自頁面請求中的token與session中的token是否一致
判斷,如果一致則提交成功并移除session中的token,不一致則說明重復提交并記錄日志
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Token { boolean save() default false; boolean remove() default false; }
@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; } }
<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 用于驗證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
<input type="hidden" name="token" value="${sessionScope.token}">
攔截器攔截請求,將上一次請求的url和參數和這次的對比
判斷,是否一致說明重復提交并記錄日志
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SameUrlData { }
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)) {//如果重復相同數據 response.sendRedirect("/error/409"); return false; } else { return true; } } return true; } else { return super.preHandle(request, response, handler); } } /** * 驗證同一個url數據是否相同提交 ,相同返回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) { //如果上一個數據為null,表示還沒有訪問頁面 httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams); return false; } else { //否則,已經訪問過頁面 if (preUrlParams.toString().equals(nowUrlParams)) { //如果上次url+數據和本次url+數據相同,則表示城府添加數據 return true; } else { //如果上次 url+數據 和本次url加數據不同,則不是重復提交 httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams); return false; } } } }
<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 { //..... }
關于springmvc中如何防止表單重復提交就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。