spring mvc防止表单重复提交的代码片段
1.定义一个token接口
1 package com.bigbigrain.token; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.Target; 6 import java.lang.annotation.ElementType; 7 import java.lang.annotation.RetentionPolicy; 8 9 @Target({ElementType.METHOD}) 10 @Retention(RetentionPolicy.RUNTIME) 11 @Documented 12 public @interface Token { 13 boolean save() default false; 14 15 boolean remove() default false; 16 }
2.实现拦截器
1 package com.bigbigrain.token; 2 3 import java.lang.reflect.Method; 4 import java.util.UUID; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.apache.log4j.Logger; 10 import org.springframework.web.method.HandlerMethod; 11 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 12 13 public class TokenInterceptor extends HandlerInterceptorAdapter { 14 private static final Logger LOG = Logger.getLogger(Token.class); 15 @Override 16 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 17 if (handler instanceof HandlerMethod) { 18 HandlerMethod handlerMethod = (HandlerMethod) handler; 19 Method method = handlerMethod.getMethod(); 20 Token annotation = method.getAnnotation(Token.class); 21 if (annotation != null) { 22 boolean needSaveSession = annotation.save(); 23 if (needSaveSession) { 24 request.getSession(true).setAttribute("token", UUID.randomUUID().toString()); 25 } 26 boolean needRemoveSession = annotation.remove(); 27 if (needRemoveSession) { 28 if (isRepeatSubmit(request)) { 29 LOG.warn("please don't repeat submit,url:"+ request.getServletPath()); 30 return false; 31 } 32 request.getSession(true).removeAttribute("token"); 33 } 34 } 35 return true; 36 } else { 37 return super.preHandle(request, response, handler); 38 } 39 } 40 41 private boolean isRepeatSubmit(HttpServletRequest request) { 42 String serverToken = (String) request.getSession(true).getAttribute("token"); 43 if (serverToken == null) { 44 return true; 45 } 46 String clinetToken = request.getParameter("token"); 47 if (clinetToken == null) { 48 return true; 49 } 50 if (!serverToken.equals(clinetToken)) { 51 return true; 52 } 53 return false; 54 } 55 }
3.配置文件配置
1 ~<!-- 拦截器配置 --> 2 <mvc:interceptors> 3 <!-- 配置Token拦截器,防止用户重复提交数据 --> 4 <mvc:interceptor> 5 <mvc:mapping path="/**"/><!--这个地方时你要拦截得路径 我这个意思是拦截所有得URL--> 6 <bean class="com.dinfo.interceptor.TokenInterceptor"/><!--class文件路径改成你自己写得拦截器路径!! --> 7 </mvc:interceptor> 8 </mvc:interceptors>
4.在跳转需要生成token页面的controller的方法加上注解~@Token(save=true);页面加上~<input type="hidden" name="token" value="${token}" />;在页面提交处理方法上加上~@Token(remove=true)注解 ===========》》》》》
不定期会发布一些实用的Java开发文章