一般提交FORM时,如果采用JS提交,而按钮则要采用BUTTON而不是SUBMIT,最好在点击后再置灰。
或者:
@每次请求时产生一个token(一般为时间戳),存于session中并随之用hidden提交,在servlet中判断接收到的token和session中的是否一致来判断是否重复提交,如果不是则重新产生一个token存于session中覆盖原来的token。
@当用户返回或者刷新重复请求servlet时,servlet判断token是否一致,由于请求方没有产生新的token,所以和servlet新产生的token不一致,认为重复提交。
@当用户在请求页面刷新也就是重新在请求页面产生token,这时新的token覆盖servlet产生的token,这时token一致,认为是一个新的请求。
请求的jsp页面代码:
@
03 | long token=System.currentTimeMillis(); //产生时间戳的token |
04 | session.setAttribute("token",token); |
07 | < form action = "isRepeat" method = "post" > |
08 | < input type = "text" name = "username" /> |
09 | < input type = "text" name = "password" /> |
10 | < input type = "hidden" value="<%=token %>" name="token"/> |
11 | < input type = "submit" value = "提交" /> |
servlet页面代码:
@
01 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) |
02 | throws ServletException, IOException { |
03 | req.setCharacterEncoding( "utf-8" ); |
04 | resp.setCharacterEncoding( "utf-8" ); |
05 | resp.setContentType( "text/html,charset=utf-8" ); |
06 | String username=req.getParameter( "username" ); |
07 | String password=req.getParameter( "password" ); |
08 | long token=Long.parseLong(req.getParameter( "token" )); |
09 | long tokenInSession=Long.parseLong(req.getSession().getAttribute( "token" )+ "" ); |
10 | if (token==tokenInSession){ |
11 | resp.getWriter().println( "ok " ); |
13 | req.getSession().setAttribute( "token" , System.currentTimeMillis()); |
19 | resp.getWriter().println( "do not repeat submit" ); |