Posted on 2011-08-04 14:14
Cana 閱讀(314)
評(píng)論(0) 編輯 收藏 所屬分類:
jsp
servlet頁面代碼:@每次請(qǐng)求時(shí)產(chǎn)生一個(gè)token(一般為時(shí)間戳),存于session中并隨之用hidden提交,在servlet中判斷接收到的token和session中的是否一致來判斷是否重復(fù)提交,如果不是則重新產(chǎn)生一個(gè) token存于session中覆蓋原來的token。
@當(dāng)用戶返回或者刷新重復(fù)請(qǐng)求servlet時(shí),servlet判斷token是否一致,由于請(qǐng)求方?jīng)]有產(chǎn)生新的token,所以和servlet新產(chǎn)生的token不一致,認(rèn)為重復(fù)提交。
@當(dāng)用戶在請(qǐng)求頁面刷新也就是重新在請(qǐng)求頁面產(chǎn)生token,這時(shí)新的token覆蓋servlet產(chǎn)生的token,這時(shí)token一致,認(rèn)為是一個(gè)新的請(qǐng)求。
@請(qǐng)求的jsp頁面代碼:
<body>
<%
long token=System.currentTimeMillis(); //產(chǎn)生時(shí)間戳的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 ");
//如果是第一次請(qǐng)求,則產(chǎn)生新的token
req.getSession().setAttribute("token", System.currentTimeMillis());
}
else
{
resp.getWriter().println("do not repeat submit");
}
}