springMVC 防止表单重复提交

原理:在新建页面中Session保存token随机码,当保存时验证,通过后删除,当再次点击保存时由于服务器端的Session中已经不存在了,所有无法验证通过。

新建注解:Token.java

packagegov.saxmz.one.controller;

importjava.lang.annotation.ElementType;

importjava.lang.annotation.Retention;

importjava.lang.annotation.RetentionPolicy;

importjava.lang.annotation.Target;

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public@interfaceToken{

booleansave()defaultfalse;

booleanremove()defaultfalse;

}

新建拦截器:TokenInterceptor.java

packagegov.saxmz.one.controller;

importjava.lang.reflect.Method;

importjava.util.UUID;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.springframework.web.method.HandlerMethod;

importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;

publicclassTokenInterceptorextendsHandlerInterceptorAdapter{

@Override

publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{

if(handlerinstanceofHandlerMethod){

HandlerMethodhandlerMethod=(HandlerMethod)handler;

Methodmethod=handlerMethod.getMethod();

Tokenannotation=method.getAnnotation(Token.class);

if(annotation!=null){

booleanneedSaveSession=annotation.save();

if(needSaveSession){

request.getSession(false).setAttribute("token",UUID.randomUUID().toString());

}

booleanneedRemoveSession=annotation.remove();

if(needRemoveSession){

if(isRepeatSubmit(request)){

returnfalse;

}

request.getSession(false).removeAttribute("token");

}

}

returntrue;

}else{

returnsuper.preHandle(request,response,handler);

}

}

privatebooleanisRepeatSubmit(HttpServletRequestrequest){

StringserverToken=(String)request.getSession(false).getAttribute("token");

if(serverToken==null){

returntrue;

}

StringclinetToken=request.getParameter("token");

if(clinetToken==null){

returntrue;

}

if(!serverToken.equals(clinetToken)){

returntrue;

}

returnfalse;

}

}

在Spring-MVC.xml中配置:

<!--拦截器配置-->

<mvc:interceptors>

<mvc:interceptor>

<mvc:mappingpath="/**"/>

<beanclass="gov.saxmz.one.controller.TokenInterceptor"/>

</mvc:interceptor>

</mvc:interceptors>

在相关方法中加入注解:

在需要生成token的controller上增加@Token(save=true),而在需要检查重复提交的controller上添加@Token(remove=true)就可以了。

在jsp页面中加入:

<inputtype="hidden"name="token"value="${token}">

相关推荐