spring 拦截器实自定义标签 防止重复提交

package test.demo.token;

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 create() default false ;
 
     boolean validate() default false ;
     
     boolean reply() default false ;
     
}



package test.demo.token;

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.handler.HandlerInterceptorAdapter;
import com.util.MethodUtil;
//拦截器类
public class TokenInterceptor 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) {
				if (annotation.create()) {
					request.getSession(false).setAttribute("token", UUID.randomUUID().toString() );
				}
				if (annotation.validate()) {
					if (isRepeatSubmit(request)) {
						if(annotation.reply()) writeMessageUtf8(response);
						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;
	}

	private void writeMessageUtf8(HttpServletResponse response) throws Exception {
		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(MethodUtil.toJson("REPEAT"));
		} finally {
			response.getWriter().close();
		}
	}
}



页面form里加:
<input type="hidden" name="token" value="${token}" />


@Token(create=true)//mvc里,进入页面前的方法上面加此


@Token(validate=true)//mvc里提交方法上面加此


spring 配置文件里加:

    <mvc:interceptors>
        <!-- 配置Token拦截器,防止用户重复提交数据 -->
		<mvc:interceptor >
			<mvc:mapping path = "/com/xxx/**" />
			<bean class = "test.demo.token.TokenInterceptor" />
		</mvc:interceptor >
    </mvc:interceptors>

你可能感兴趣的:(spring)