在首页看到基于前段并行控制的表单重复提交限制,觉得不用那么复杂,再此献上后端限制代码
1)注解类
package plus.jfinal.annotations; import java.lang.annotation.*; /** * 重复提交Token */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface DuplicateSubmitToken { /** * 3s 超时 * @return */ long limit() default 3000; }
2)拦截器
package plus.jfinal.core.interceptor; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import plus.jfinal.annotations.DuplicateSubmitToken; import plus.jfinal.entitys.Result; public class DuplicateSubmitInterceptor implements Interceptor { @Override public void intercept(Invocation inv) { DuplicateSubmitToken token = inv.getMethod().getAnnotation(DuplicateSubmitToken.class); Controller controller = inv.getController(); String key = "token;"+inv.getActionKey(); if(token!=null){ Object t = controller.getSession().getAttribute(key); if(t == null){ controller.getSession().setAttribute(key,System.currentTimeMillis()); }else{ long time = Long.parseLong(t.toString()); long surplus = System.currentTimeMillis()-time; if(surplus > token.limit()){ controller.getSession().setAttribute(key,System.currentTimeMillis()); }else{ controller.renderJson(new Result().setFail(430, String.format("禁止重复提交,两次提交时间间隔( %s 秒 ),还需等待 %s 秒", token.limit()/1000,(token.limit()-surplus)/1000))); return ; } } } inv.invoke(); if(token!=null){ controller.getSession().setAttribute(key,System.currentTimeMillis()); } } }
使用方式:
# JFinalConfig 添加 public void configInterceptor(Interceptors me) { me.add(new DuplicateSubmitInterceptor()); ... } # 具体控制层添加 @DuplicateSubmitToken public void index(){ ... }
打完收枪~