通过session 怎么防止表单的重复提交!
1.在提交表单的时候使用隐藏域;
String tokenValue=new Date().getTime();
<input type="hidden" name="token" value="<%=tokenValue%>"/>
2.往session中添加一个随机值;
request.getSession().setAttribute("token",tokenValue);
3.在servlet中对隐藏域的值和session中的值作比较;
servlet 中
String tokenValue=request.getParameter("token");
String sessionToken=request.getSeesion().getAttribute("token");
if(sessionToken !=null && ressionToken.equals(tokenValue)){
request.getSession().removeAttribute("token");
}
1 <%@ page import="java.util.Date" %><%-- 2 Created by IntelliJ IDEA. 3 User: ty 4 Date: 2017/4/12 5 Time: 11:17 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <htm/l> 10 <head> 11 <title>Title</title> 12 </head> 13 <body> 14 <% 15 String tokenValue=new Date().getTime()+""; 16 request.getSession().setAttribute("token",tokenValue); 17 %> 18 19 <form action="<%=request.getContextPath()%>/token1" method="post"> 20 <input type="hidden" name="token" value="<%=tokenValue%>" /> 21 username:<input type="text" name="username"/> <br> 22 <input type="submit" value="submit"> 23 24 </form> 25 </body> 26 </html>
package main.java.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by ty on 2017/4/12. */ @WebServlet(name = "TokenProcessServlet",urlPatterns = "/token1") public class TokenProcessServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } String username = request.getParameter("username"); String tokenValue = request.getParameter("token"); Object sessionToken = request.getSession().getAttribute("token"); response.getWriter().print("sessionToken===="+sessionToken+">>>"); System.out.println("tokenValue="+tokenValue); System.out.println("sessionToken="+sessionToken); if(sessionToken != null && sessionToken.equals(tokenValue)) { request.getSession().removeAttribute("token"); response.sendRedirect(request.getContextPath()+"/successful.jsp"); }else{ response.sendRedirect(request.getContextPath()+"/error1.jsp"); return ; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }