关于用session做一个防范表单重复提交的例子的问题
我这个表单提交的原理是:
(1)通过一个servlet(a)访问到一个表单,在servlet跳转到表单之前,就在session作用域中生成一个tooken属性
session.setAttribute("tooken", Math.random()+""); (随机数可能会重复,但不影响例子演示。)
(2)在表单页面中用一个hidden组件接收session作用域中的tooken属性
(3)表单提交到servlet(b)时,首先拿到表单中hidden组件中的tooken属性,再获取session作用域中的tooken属性,将两个进行对比,如果一样,则将session作用域中的tooken删除
session.removeAttribute("tooken");
以下是具体代码:
Servlet a
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("tooken", Math.random()+"");
response.sendRedirect(request.getContextPath()+"/a.jsp");
}
<form action="${pageContext.request.contextPath}/servlet/b" method="post">
<input type="text" name="tooken" value="${tooken}">
<input type="submit" value="发送">
</form>
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {//这里加入了延迟
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String tooken = request.getParameter("tooken");
String tooken_session = (String)request.getSession().getAttribute("tooken");
System.out.println("request的tooken---------"+tooken);
System.out.println("session的tooken---------"+tooken_session);
if(tooken_session.equals(tooken)){
request.getSession().removeAttribute("tooken");
}
}