2015-12-10

    http://blog.icoolxue.com/submitted-by-spring-mvc-to-prevent-data-duplication/

    我的代码示例:
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Token {

    1. boolean save() default false;
    2. boolean remove() default false;<br />}<br />public class TokenInterceptor extends HandlerInterceptorAdapter {
    3. private static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
    4. @Override<br /> public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<br /> if (handler instanceof HandlerMethod) {<br /> HandlerMethod handlerMethod = (HandlerMethod) handler;<br /> Method method = handlerMethod.getMethod();<br /> Token annotation = method.getAnnotation(Token.class);<br /> if (annotation != null) {<br /> boolean needSaveSession = annotation.save();<br /> if (needSaveSession) {<br /> request.getSession(false).setAttribute("token", UUID.randomUUID().toString());<br /> }<br /> boolean needRemoveSession = annotation.remove();<br /> if (needRemoveSession) {<br /> if (isRepeatSubmit(request)) {<br /> logger.debug("拦截到重复提交");<br /> return false;<br /> }<br /> request.getSession(false).removeAttribute("token");<br /> }<br /> }<br /> return true;<br /> } else {<br /> return super.preHandle(request, response, handler);<br /> }<br /> }
    5. private boolean isRepeatSubmit(HttpServletRequest request) {<br /> String serverToken = (String) request.getSession(false).getAttribute("token");<br /> if (serverToken == null) {<br /> return true;<br /> }<br /> String clinetToken = request.getParameter("token");<br /> if (clinetToken == null) {<br /> return true;<br /> }<br /> if (!serverToken.equals(clinetToken)) {<br /> return true;<br /> }<br /> return false;<br /> }<br />}






    @Token(save=true,remove = false) 跳转页面使用

    @Token(save=false,remove = true) 提交按钮使用