SpringMVC 防重复提交拦截
/** * Created with IntelliJ IDEA. * User: lijian * Date: 14-7-11 * Time: 上午10:38 * description :防止重复提交数据 http://hi.baidu.com/uvmfawxtxzbknqe/item/3c87d4220acba32442634acf * To change this template use File | Settings | File Templates. */ public class TokenInterceptor extends HandlerInterceptorAdapter { private static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); Token annotation = method.getAnnotation(Token.class); if (annotation != null) { boolean needSaveSession = annotation.save(); if (needSaveSession) { request.getSession(false).setAttribute("token", UUID.randomUUID().toString()); } boolean needRemoveSession = annotation.remove(); if (needRemoveSession) { if (isRepeatSubmit(request)) { return false; } request.getSession(false).removeAttribute("token"); } } return true; } else { return super.preHandle(request, response, handler); } } private boolean isRepeatSubmit(HttpServletRequest request) { String serverToken = (String) request.getSession(false).getAttribute("token"); if (serverToken == null) { return true; } String clinetToken = request.getParameter("token"); if (clinetToken == null) { return true; } if (!serverToken.equals(clinetToken)) { return true; } return false; } }
//在请求道form页面添加自定义注解@Token(save=true)用以添加uuid生成的唯一值 //页面上添加<input type="hidden" name="token" value="${token}" /> //在提交时候有需要在提交的Controller上添加@Token(remove=true)
/** * Created with IntelliJ IDEA. * User: lijian * Date: 14-7-11 * Time: 上午10:35 * To change this template use File | Settings | File Templates. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Token { /** * 生成唯一的uuid TOKEN值 * * @return */ boolean save() default false; /** * 校验TOKEN值,通过校验移除TOKEN值 * * @return */ boolean remove() default false; }
<!-- 拦截器配置 --> <mvc:interceptors> <!-- 配置Token拦截器,防止用户重复提交数据 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.xxxx.xxx.xxx.TokenInterceptor"/> </mvc:interceptor> </mvc:interceptors>
配置文件中放置的文件
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。