@每次请求时产生一个token(一般为时间戳),存于session中并随之用hidden提交,在servlet中判断接收到的token和session中的是否一致来判断是否重复提交,如果不是则重新产生一个token存于session中覆盖原来的token。
@当用户返回或者刷新重复请求servlet时,servlet判断token是否一致,由于请求方没有产生新的token,所以和servlet新产生的token不一致,认为重复提交。
@当用户在请求页面刷新也就是重新在请求页面产生token,这时新的token覆盖servlet产生的token,这时token一致,认为是一个新的请求。
请求的jsp页面代码:
@
long token=System.currentTimeMillis(); //产生时间戳的token
session.setAttribute("token",token);
%>
servlet页面代码:
@
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html,charset=utf-8");
String username=req.getParameter("username");
String password=req.getParameter("password");
long token=Long.parseLong(req.getParameter("token"));
long tokenInSession=Long.parseLong(req.getSession().getAttribute("token")+"");
if(token==tokenInSession){
resp.getWriter().println("ok ");
//如果是第一次请求,则产生新的token
req.getSession().setAttribute("token", System.currentTimeMillis());
}
else
{
resp.getWriter().println("do not repeat submit");
}
}