利用Spring MVC的过滤器及token传递验证来实现表单防重复提交。
创建注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public@interfaceToken{
booleancreate()defaultfalse;
booleanremove()defaultfalse;
}
在跳转页面的方法上加上:@Token(create = true)\
在提交的action方法上加上:@Token(remove = true)
创建过滤器
publicclassTokenInterceptorextendsHandlerInterceptorAdapter{
privateLoggerlogger=Logger.getLogger(TokenInterceptor.class);
privatestaticfinalStringTOKEN="token";
@Override
publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,
Objecthandler)throwsException{
if(handlerinstanceofHandlerMethod){
Methodmethod=((HandlerMethod)handler).getMethod();
Tokenannotation=method.getAnnotation(Token.class);
if(annotation!=null){
HttpSessionsession=request.getSession();
// 创建token
booleancreate=annotation.create();
if(create){
session.setAttribute(TOKEN,UUID.randomUUID().toString());
returntrue;
}
// 删除token
booleanremove=annotation.remove();
if(remove){
if(isRepeatSubmit(request)){
logger.warn("表单不能重复提交:"+request.getRequestURL());
returnfalse;
}
session.removeAttribute(TOKEN);
}
}
}else{
returnsuper.preHandle(request,response,handler);
}
returntrue;
}
privatebooleanisRepeatSubmit(HttpServletRequestrequest){
Stringtoken=(String)request.getSession().getAttribute(TOKEN);
if(token==null){
returntrue;
}
StringreqToken=request.getParameter(TOKEN);
if(reqToken==null){
returntrue;
}
if(!token.equals(reqToken)){
returntrue;
}
returnfalse;
}
}
配置拦截器
表单添加token
在form表单里面添加token域,提交表单时需要传过去。