当前位置: 代码迷 >> JavaScript >> Jsp 防止二次交付(重复提交)
  详细解决方案

Jsp 防止二次交付(重复提交)

热度:189   发布时间:2012-10-06 17:34:01.0
Jsp 防止二次提交(重复提交)

servlet页面代码:@每次请求时产生一个token(一般为时间戳),存于session中并随之用hidden提交,在servlet中判断接收到的token和session中的是否一致来判断是否重复提交,如果不是则重新产生一个 ? token存于session中覆盖原来的token。

@当用户返回或者刷新重复请求servlet时,servlet判断token是否一致,由于请求方没有产生新的token,所以和servlet新产生的token不一致,认为重复提交。

@当用户在请求页面刷新也就是重新在请求页面产生token,这时新的token覆盖servlet产生的token,这时token一致,认为是一个新的请求。

@请求的jsp页面代码:
<body>
????
<%
???????????
long?token=System.currentTimeMillis();????//产生时间戳的token
????????????session.setAttribute("token",token);????
???????????
????
%>
????
<form??action="isRepeat"?method="post">
????????
<input?type="text"??name="username"/>
????????
<input?type="text"??name="password"/>
????????
<input?type="hidden"?value="<%=token?%>"?name="token"/>???<!--?作为hidden提交?-->
????????
<input?type="submit"?value="提交"/>
????
</form>
</body>

?

@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");?
?????????}
????}

  相关解决方案