1. 程式人生 > >避免表單重複提交--用session實現token機制

避免表單重複提交--用session實現token機制

直接拿例子來說吧!!

目錄結構


web.xml

    <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>  
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
      <display-name>javaWeb_25</display-name>  
      <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
      </welcome-file-list>  
    </web-app></span>  

index.jsp

   <span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"  
        pageEncoding="UTF-8"%>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>index.jsp</title>  
    </head>  
    <body>  
        <form action="<%=request.getContextPath() %>/tokenServlet" method="post">  
            name: <input type="text" name="name"><br>  
            <input type="submit" value="提交">  
          
        </form>  
    </body>  
    </html></span>  



TokenServlet.java
<span style="font-size:18px;">package com.dao.chu;  
  
import java.io.IOException;  
  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
/** 
 * Servlet implementation class TokenServlet 
 */  
@WebServlet("/tokenServlet")  
public class TokenServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public TokenServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
          
        String name = request.getParameter("name");  
          
        System.out.println("name is :"+name);  
          
        request.getRequestDispatcher("/success.jsp").forward(request, response);  
    }  
  
}


success.jsp
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>success.jsp</title>  
</head>  
<body>  
    <h1>success page</h1>  
</body>  
</html></span> 


執行效果


提交表單一次,並且重新整理三次頁面


這就是表單的重複提交

重複提交的情況:

①在表單提交到一個Servlet而Servlet又通過請求轉發的方式響應了一個jsp或者是html頁面,此時位址列還保留著Servlet的路徑,在響應頁面點選重新整理。

②在響應頁面沒有到達時,重複點選提交按鈕。

③點選返回,再點選提交

不是重複提交的情況

①點選返回,重新整理原表單頁面,再點選提交

如何避免表單的重複提交

在表單中做一個標記,提交到Servlet時,檢查標記是否存在且是否和預定的標記一致,若一致,則受理請求,並銷燬標記,若不一致,則直接響應提示資訊:重複提交。

1.只寫一個一個隱藏逾

<input type="hidden" name="token" value="daochuwenziyao">,不行。因為無法銷燬標記。

2.標記放在request中

各檔案修改如下:


index.jsp

    <span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"  
        pageEncoding="UTF-8"%>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>index.jsp</title>  
    </head>  
    <body>  
      
      
        <form action="<%=request.getContextPath() %>/tokenServlet" method="post">  
          
        <%  
            request.setAttribute("token", "daochuwenizyao");  
        %>  
            name: <input type="text" name="name"><br>  
              
            <input type="submit" value="提交">  
          
        </form>  
    </body>  
    </html></span>  

TokenServlet

package com.dao.chu;  
  
import java.io.IOException;  
  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
/** 
 * Servlet implementation class TokenServlet 
 */  
@WebServlet("/tokenServlet")  
public class TokenServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public TokenServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
          
        String name = request.getParameter("name");  
        Object token =  request.getAttribute("token");  
          
        if (token!=null) {  
              
            request.removeAttribute("token");  
              
        }else {  
            response.sendRedirect(request.getContextPath()+"/token.jsp");;  
        }  
          
          
          
    }  
  
} 


token.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>token.jsp</title>  
</head>  
<body>  
  
    <h3>對不起,您已經提交過了</h3>  
</body>  
</html>


也不行,因為表單頁面重新整理後request已經被銷燬,再提交表單是一個新的request。


3.標記放在session中.


index.jsp

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>index.jsp</title>  
</head>  
<body>  
  
  
    <form action="<%=request.getContextPath() %>/tokenServlet" method="post">  
      
    <%  
        session.setAttribute("token", "daochuwenizyao");  
    %>  
        name: <input type="text" name="name"><br>  
          
        <input type="submit" value="提交">  
      
    </form>  
</body>  
</html></span> 

TokenServlet.Java

package com.dao.chu;  
  
import java.io.IOException;  
  
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 javax.servlet.http.HttpSession;  
  
/** 
 * Servlet implementation class TokenServlet 
 */  
@WebServlet("/tokenServlet")  
public class TokenServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public TokenServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
          
        HttpSession session = request.getSession();  
          
        Object token =  session.getAttribute("token");  
          
        if (token!=null) {  
              
            session.removeAttribute("token");  
              
        }else {  
            response.sendRedirect(request.getContextPath()+"/token.jsp");;  
        }  
          
          
          
    }  
  
}



經過檢測,此方法可行。

但是有時候我們需要往session中放一個隨機值,後臺如何取得該隨機值呢,這時候需要和隱藏逾搭配使用。

index.jsp

    <span style="font-size:18px;"><%@page import="java.util.Date"%>  
    <%@ page language="java" contentType="text/html; charset=UTF-8"  
        pageEncoding="UTF-8"%>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>index.jsp</title>  
    </head>  
    <body>  
        <%  
            String tokenValue = new Date().getTime() + "";  
            session.setAttribute("token", tokenValue);  
        %>  
      
        <form action="<%=request.getContextPath() %>/tokenServlet" method="post">  
          
            <input type="hidden" name="token" value="<%=tokenValue %>">  
          
            name: <input type="text" name="name"><br>  
              
            <input type="submit" value="提交">  
          
        </form>  
    </body>  
    </html></span>  



TokenServlet.java
package com.dao.chu;  
  
import java.io.IOException;  
import java.util.Date;  
  
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 javax.servlet.http.HttpSession;  
  
/** 
 * Servlet implementation class TokenServlet 
 */  
@WebServlet("/tokenServlet")  
public class TokenServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public TokenServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
          
        HttpSession session = request.getSession();  
          
        String tokenValue = request.getParameter("token");  
        String token = (String)session.getAttribute("token");  
          
          
        if (token!=null && token.equals(tokenValue)) {  
              
            session.removeAttribute("token");  
              
        }else {  
            response.sendRedirect(request.getContextPath()+"/token.jsp");;  
        }  
          
          
          
    }  
  
}


經過檢測,此方法可行。並且更加滿足需求。

步驟:

1.在原表單頁面,生成一個隨機數token

2.在原表單頁面,把token放在session屬性中

3.在原表單頁面,把token值放在隱藏逾中

4.在目標Servlet中,獲取session和隱藏逾中的token值

5.比較兩個值是否一致,若一致,受理請求且把session中的token屬性清除,若不一致則直接顯示提示頁面:重複提交

使用strus1的工具類來編寫程式碼

strus1的工具類

下載地址

http://download.csdn.NET/download/zhangyw31/2706595

開啟

G:\struts-1.2.9-src\src\share\org\apache\struts\util\TokenProcessor.java

將TokenProcessor複製到專案中,修改兩個常量即可。如果好奇可以在G:\struts-1.2.9-src\src\share\org\apache\struts\Globals中可以搜尋到。

最終我們修改成如下檔案:

TokenProcessor.java

    /* 
     * $Id: TokenProcessor.java 54929 2004-10-16 16:38:42Z germuska $  
     * 
     * Copyright 2003-2004 The Apache Software Foundation. 
     *  
     * Licensed under the Apache License, Version 2.0 (the "License"); 
     * you may not use this file except in compliance with the License. 
     * You may obtain a copy of the License at 
     *  
     *      http://www.apache.org/licenses/LICENSE-2.0 
     *  
     * Unless required by applicable law or agreed to in writing, software 
     * distributed under the License is distributed on an "AS IS" BASIS, 
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
     * See the License for the specific language governing permissions and 
     * limitations under the License. 
     */  
      
    package com.dao.chu;  
      
    import java.security.MessageDigest;  
    import java.security.NoSuchAlgorithmException;  
      
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpSession;  
      
      
    /** 
     * TokenProcessor is responsible for handling all token related functionality.  The  
     * methods in this class are synchronized to protect token processing from multiple 
     * threads.  Servlet containers are allowed to return a different HttpSession object 
     * for two threads accessing the same session so it is not possible to synchronize  
     * on the session. 
     *  
     * @since Struts 1.1 
     */  
    public class TokenProcessor {  
      
        private static final String TOKEN_KEY = null;  
        private static final String TRANSACTION_TOKEN_KEY = null;  
        /** 
         * The singleton instance of this class. 
         */  
        private static TokenProcessor instance = new TokenProcessor();  
      
        /** 
         * Retrieves the singleton instance of this class. 
         */  
        public static TokenProcessor getInstance() {  
            return instance;  
        }  
      
        /** 
         * Protected constructor for TokenProcessor.  Use TokenProcessor.getInstance() 
         * to obtain a reference to the processor. 
         */  
        protected TokenProcessor() {  
            super();  
        }  
      
        /** 
         * The timestamp used most recently to generate a token value. 
         */  
        private long previous;  
      
        /** 
         * Return <code>true</code> if there is a transaction token stored in 
         * the user's current session, and the value submitted as a request 
         * parameter with this action matches it.  Returns <code>false</code> 
         * under any of the following circumstances: 
         * <ul> 
         * <li>No session associated with this request</li> 
         * <li>No transaction token saved in the session</li> 
         * <li>No transaction token included as a request parameter</li> 
         * <li>The included transaction token value does not match the 
         *     transaction token in the user's session</li> 
         * </ul> 
         * 
         * @param request The servlet request we are processing 
         */  
        public synchronized boolean isTokenValid(HttpServletRequest request) {  
            return this.isTokenValid(request, false);  
        }  
      
        /** 
         * Return <code>true</code> if there is a transaction token stored in 
         * the user's current session, and the value submitted as a request 
         * parameter with this action matches it.  Returns <code>false</code> 
         * <ul> 
         * <li>No session associated with this request</li> 
         * <li>No transaction token saved in the session</li> 
         * <li>No transaction token included as a request parameter</li> 
         * <li>The included transaction token value does not match the 
         *     transaction token in the user's session</li> 
         * </ul> 
         * 
         * @param request The servlet request we are processing 
         * @param reset Should we reset the token after checking it? 
         */  
        public synchronized boolean isTokenValid(  
            HttpServletRequest request,  
            boolean reset) {  
      
            // Retrieve the current session for this request  
            HttpSession session = request.getSession(false);  
            if (session == null) {  
                return false;  
            }  
      
            // Retrieve the transaction token from this session, and  
            // reset it if requested  
            String saved = (String) session.getAttribute(TRANSACTION_TOKEN_KEY);  
            if (saved == null) {  
                return false;  
            }  
      
            if (reset) {  
                this.resetToken(request);  
            }  
      
            // Retrieve the transaction token included in this request  
            String token = request.getParameter(TOKEN_KEY);  
            if (token == null) {  
                return false;  
            }  
      
            return saved.equals(token);  
        }  
      
        /** 
         * Reset the saved transaction token in the user's session.  This 
         * indicates that transactional token checking will not be needed 
         * on the next request that is submitted. 
         * 
         * @param request The servlet request we are processing 
         */  
        public synchronized void resetToken(HttpServletRequest request) {  
      
            HttpSession session = request.getSession(false);  
            if (session == null) {  
                return;  
            }  
            session.removeAttribute(TRANSACTION_TOKEN_KEY);  
        }  
      
        /** 
         * Save a new transaction token in the user's current session, creating 
         * a new session if necessary. 
         * 
         * @param request The servlet request we are processing 
         */  
        public synchronized void saveToken(HttpServletRequest request) {  
      
            HttpSession session = request.getSession();  
            String token = generateToken(request);  
            if (token != null) {  
                session.setAttribute(TRANSACTION_TOKEN_KEY, token);  
            }  
      
        }  
      
        /** 
         * Generate a new transaction token, to be used for enforcing a single 
         * request for a particular transaction. 
         *  
         * @param request The request we are processing 
         */  
        public synchronized String generateToken(HttpServletRequest request) {  
      
            HttpSession session = request.getSession();  
            try {  
                byte id[] = session.getId().getBytes();  
                long current = System.currentTimeMillis();  
                if (current == previous) {  
                    current++;  
                }  
                previous = current;  
                byte now[] = new Long(current).toString().getBytes();  
                MessageDigest md = MessageDigest.getInstance("MD5");  
                md.update(id);  
                md.update(now);  
                return toHex(md.digest());  
            } catch (NoSuchAlgorithmException e) {  
                return null;  
            }  
      
        }  
      
        /** 
         * Convert a byte array to a String of hexadecimal digits and return it. 
         * @param buffer The byte array to be converted 
         */  
        private String toHex(byte buffer[]) {  
            StringBuffer sb = new StringBuffer(buffer.length * 2);  
            for (int i = 0; i < buffer.length; i++) {  
                sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));  
                sb.append(Character.forDigit(buffer[i] & 0x0f, 16));  
            }  
            return sb.toString();  
        }  
      
    }  

專案結構


index.jsp

    <span style="font-size:18px;"><%@page import="com.dao.chu.TokenProcessor"%>  
    <%@page import="java.util.Date"%>  
    <%@ page language="java" contentType="text/html; charset=UTF-8"  
        pageEncoding="UTF-8"%>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>index.jsp</title>  
    </head>  
    <body>  
      
        <form action="<%=request.getContextPath() %>/tokenServlet" method="post">  
          
            <!-- 兩個作用   
                1.產生一個隨機值  
                2.tokenValue放在session中  
              
            -->  
            <input type="hidden" name="TOKEN_KEY" value="<%=TokenProcessor.getInstance().saveToken(request) %>">  
          
            name: <input type="text" name="name"><br>  
              
            <input type="submit" value="提交">  
          
        </form>  
    </body>  
    </html></span>  

TokenServlet.java

package com.dao.chu;  
  
import java.io.IOException;  
import java.util.Date;  
  
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 javax.servlet.http.HttpSession;  
  
/** 
 * Servlet implementation class TokenServlet 
 */  
@WebServlet("/tokenServlet")  
public class TokenServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public TokenServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
          
        boolean tokenValid = TokenProcessor.getInstance().isTokenValid(request);  
          
          
        if (tokenValid) {  
              
            TokenProcessor.getInstance().resetToken(request);  
        }  
        else {  
              
            response.sendRedirect(request.getContextPath()+"/token.jsp");;  
        }  
          
    }  
  
}

可以看出這樣寫程式碼複用性很高。

執行效果

正常情況下可以提交,一旦發生重複提交,則會跳轉到另外一個頁面。


轉自http://blog.csdn.net/daochuwenziyao/article/details/60592188