JFinal 本身有通过validateToken() 验证重复提交,也有通过页面 js 来控制重复提交的方式,现在发一个后端限时重复提交的代码:
1、MainConfig 的 configPlugin 设置 ehcache:
me.add(new EhCachePlugin());
2、创建一个Interceptor :
public class RepeatIntercetpor implements Interceptor {
//重复提交间隔时间
private final static long timeOut = 2000;
@Override
public void intercept(Invocation inv) {
ReturnJson rJson = new ReturnJson();
UserClient user = inv.getController().getAttr("user");
String className = inv.getController().getClass().getName();
String methodName = inv.getMethodName();
String key = user.getId() + "." + className + "." + methodName;
Object o = CacheKit.get("repeat", key);
long now = System.currentTimeMillis();
if( o != null && now - Long.parseLong(o.toString()) <= timeOut ) {
System.out.println("cache:now=" + now);
rJson.setStatus(-1);
rJson.setMessage("请不要重复提交");
CacheKit.put("repeat", key, now);
inv.getController().renderJson( rJson );
return;
}else {
System.out.println("cache:" + key + "=" + ((o==null)? now : o.toString()));
CacheKit.put("repeat", key, now);
inv.invoke();
}
}
}其中通过timeOut来判断保存在cache里的访问时间,如果大于timeOut那么 invoke(),否则返回“请不要重复提交”信息。
3、设置ehcache.xml
<cache name="repeat" maxEntriesLocalHeap="90000" eternal="true" overflowToDisk="false"/>
4、要使用的地方调用 RepeatIntercetpor
@Before(RepeatIntercetpor.class)
public void add() {
}这样,用户通过页面调用的时候,如果在2秒内重复调用 add 方法,那么就会提示“请不要重复提交”信息。