注解防止表单重复提交

版权声明:本文为博主原创文章,转载请标明出处和链接! https://blog.csdn.net/junmoxi/article/details/84927546

1. 注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StopRepeatSubmit {
}

2. 拦截处理器

/**
 * @author pibigstar
 * @desc 防止表单重复提交拦截处理器
 **/

public class StopRepeatSubmitHandlerInterceptor 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();
            StopRepeatSubmit annotation = method.getAnnotation(StopRepeatSubmit.class);
            if (annotation!=null) {
                // 判断是否已经提交过了
                String paramter = request.getParameterMap().toString();
                String url = request.getRequestURL().toString();
                String token = url+paramter;
                Object attrToken = request.getSession().getAttribute("token");
                if (attrToken == null) {
                    // 第一次请求
                    request.getSession().setAttribute("token",token);
                    return true;
                }
                if (attrToken.toString().equals(token)){
                    // 重复提交了
                    return false;
                } else {
                    // 第一次提交
                    request.getSession().setAttribute("token",token);
                    return true;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
}

3. 使用

 @PostMapping("/submit")
 @StopRepeatSubmit
 public void submit(){
 }

猜你喜欢

转载自blog.csdn.net/junmoxi/article/details/84927546