1、配置拦截器
spring-mvc.xml
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**/*"/> <mvc:exclude-mapping path="/css/**"/> <mvc:exclude-mapping path="/images/**"/> <mvc:exclude-mapping path="/js/**"/> <mvc:exclude-mapping path="/upload/**"/> <bean class="com.tp.soft.common.interceptor.AvoidDuplicateSubmissionInterceptor" /> </mvc:interceptor> </mvc:interceptors>
2、写注解接口
Token.java
package com.tp.soft.common.interceptor; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention (RetentionPolicy.RUNTIME) public @interface Token { boolean save() default false ; boolean remove() default false ; }
3、写拦截器
AvoidDuplicateSubmissionInterceptor.java
package com.tp.soft.common.interceptor; import java.lang.reflect.Method; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class AvoidDuplicateSubmissionInterceptor 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(); 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 ; } }
4、在需要生成token的方法上写上@Token(save=true) 在重复请求的方法上写上@Token(remove=true)
5、在页面上如果是form表单写上
<input type="hidden" name="token" value="${token}" />
如果是异步的则直接用${token}传入参数