首页 > 代码库 > SpringMVC 防重复提交拦截
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=http://www.mamicode.com/"${token}" />>/** * 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>配置文件中放置的文件
SpringMVC 防重复提交拦截
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。