出現表單重復提交的三種情況:
一、服務器響應緩慢,用戶多次點擊提交按鈕。
二、提交成功後刷新頁面。
三、提交成功後返回表單頁面再次點擊提交。
package com.jalja.token; import java.io.IOException; import java.io.PrintWriter; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String contextPath=request.getContextPath(); String requestURI=request.getRequestURI(); String path=requestURI.substring(contextPath.length()+1, requestURI.length()); String token=""; if(path.equals("index.do")){ token = UUID.randomUUID().toString();//創建令牌 System.out.println("在FormServlet中生成的token:"+token); request.getSession().setAttribute("token", token); //在服務器使用session保存token(令牌) request.getRequestDispatcher("/index.jsp").forward(request, response);//跳轉到form.jsp頁面 } if(path.equals("token.do")){ String name=request.getParameter("username"); String tokenValue=request.getParameter("tokenValue");//獲取客戶端的Token System.out.println("獲取客戶端的token:"+tokenValue); String server_token = (String) request.getSession().getAttribute("token");//獲取服務器端的token if(tokenValue!=null && server_token!=null && server_token.equals(tokenValue)){ System.out.println("處理請求; 獲得name==》"+name); try { Thread.sleep(3*1000);//模擬網絡延遲 } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.println("不處理"); } request.getSession().removeAttribute("token");//每次處理玩請求都要移除掉token } } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>Form表單</title> </head> <body> <h2>防止表單重復提交</h2> <form action="${pageContext.request.contextPath}/token.do" method="post"> <input type="hidden" value="${token}" name="tokenValue"/> 用戶名:<input type="text" name="username"/> <input type="submit" value="提交" id="submit"/> </form> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>token</servlet-name> <servlet-class>com.jalja.token.UserServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>token</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>