javaWEB总结(25):避免表单的重复提交


什么是表单的重复提交?

目录结构





web.xml


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


运行效果





提交表单一次,并且刷新三次页面





这就是表单的重复提交



重复提交的情况:

①在表单提交到一个Servlet而Servlet又通过请求转发的方式响应了一个jsp或者是html页面,此时地址栏还保留着Servlet的路径,在响应页面点击刷新。

②在响应页面没有到达时,重复点击提交按钮。

③点击返回,再点击提交


不是重复提交的情况

①点击返回,刷新原表单页面,再点击提交


如何避免表单的重复提交

在表单中做一个标记,提交到Servlet时,检查标记是否存在且是否和预定的标记一致,若一致,则受理请求,并销毁标记,若不一致,则直接响应提示信息:重复提交。



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

}

可以看出这样写代码复用性很高。


运行效果

正常情况下可以提交,一旦发生重复提交,则会跳转到另外一个页面。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值