javaWEB總結(25):避免表單的重複提交


什麼是表單的重複提交?

目錄結構





web.xmlhtml


<?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>

index.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>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>

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;

/**
 * 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


<%@ 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>


運行效果





提交表單一次,而且刷新三次頁面java





這就是表單的重複提交git



重複提交的狀況:web

①在表單提交到一個Servlet而Servlet又經過請求轉發的方式響應了一個jsp或者是html頁面,此時地址欄還保留着Servlet的路徑,在響應頁面點擊刷新。express

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

③點擊返回,再點擊提交session


不是重複提交的狀況app

①點擊返回,刷新原表單頁面,再點擊提交less


如何避免表單的重複提交

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



1.只寫一個一個隱藏逾

<input type="hidden" name="token" value="daochuwenziyao">,不行。由於沒法銷燬標記。

2.標記放在request中

各文件修改以下:


index.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>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>

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

<%@ 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>


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


<%@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>

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

<%@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>

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");;
		}
		
	}

}

能夠看出這樣寫代碼複用性很高。


運行效果

正常狀況下能夠提交,一旦發生重複提交,則會跳轉到另一個頁面。


相關文章
相關標籤/搜索