防止表单的重复提交
一:客户端浏览器
我们可以使用JS(JQ),当用户提交表单后,几秒内将提交按钮设置为不可用、或者不可见,我个人不建议使用按钮不可见,这样会给用户的体验很差。
二:服务器端
实现思路:
我们可以①生成32位令牌(token)的方式,存在Session中在服务器验证,②如果为第一次提交则通过验证、并移除令牌。③如果为重复提交,令牌已经移除,阻止数据库的后续操作。
注册JSP页面(由登陆页面->tokenAction->注册页面)
<input/> type为hidden 用于存储Token值。
图片只展示了核心代码。
生成TokenStruts2的Action(或者原生Servlet)
服务器验证
源代码:
public String regist() throws Exception { // 获得值栈 ActionContext->ValueStack->去session或application 中取值。 ValueStack vs = ActionContext.getContext().getValueStack(); ControlService service = new ControlServiceImpl(); String myToken = ((String) vs.findString("#session.token"));//从Session中取出Token值 Map<String, Object> session = ActionContext.getContext().getSession(); if (token == null || myToken == null || !myToken.equals(token)) { //判断表单是否重复提交 return Action.NONE; } String code = ((String) vs.findValue("#session.code")); if (vcode == null || !code.equalsIgnoreCase(vcode)) { return Action.NONE; } else { service.add(control); session.remove("token");//移除token session.remove("code"); return Action.SUCCESS; } }