JavaWeb防止表单重复提交

//1.产生表单
package cn.ytu.form;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.ytu.session.SessionDemo1;
import sun.misc.BASE64Encoder;

//产生表单
public class FormServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 产生表单的随机数
		TokenProcess tokenprocess = TokenProcess.newInstance();
		String token = tokenprocess.generateToken();
		// 创建Session,并保持表单的随机数(表单的唯一标示码)
		request.getSession().setAttribute("token", token);
		// 跳转到jsp页面为用户输出表单,并带去表单的唯一标示码
		request.getRequestDispatcher("/form.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

// 产生一个唯一的随机数
class TokenProcess {
	/*
	 * 单例设计模式,步骤 1.把构造方法私有化 2,自己创建一个对象 3,对外暴露一个对象,允许外界获取上面创建的对象
	 */
	private TokenProcess() {
	}

	private static final TokenProcess instance = new TokenProcess();

	public static TokenProcess newInstance() {
		return instance;
	}

	// 产生随机数
	public String generateToken() {
		String token = System.currentTimeMillis() + new Random().nextInt() + ""; // 当前时间的毫秒值加上一个随机数
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			/*
			 * MessageDigest提供信息摘要算法的功能,如 MD5 或 SHA 算法.
			 * 信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
			 */
			byte[] md5 = md.digest(token.getBytes());
			// digest()方法,完成哈希计算。
			// Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5); // 返回编码后的明文字符串
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}

//2.验证表单
package cn.ytu.form;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//提交表单
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//解决乱码
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		boolean b=isTokenvalid(request);
		
		if(!b){//表单无效
			System.out.println("请不要重复提交");
			return;
		}
		//表单有效,提交成功
		request.getSession().removeAttribute("token");   //移除当前表单的唯一标识符
		/*
		 * 提交成功后,可以根据程序需求,对表单进行操作......
		 */
	}

	private boolean isTokenvalid(HttpServletRequest request) {
		String client_token=request.getParameter("token");  //获取客户机带来的表单号
		String server_token=(String) request.getSession().getAttribute("token");   //获取服务器端的表单号
		 //判断服务器端有没有产生表单号,即服务器有没有为用户创建表单
		if(server_token==null){ 
			return false;
		}
		
		//判断客户端有没有带表单号过来
		if(client_token==null){
			return false;
		}
		
		//判断客户端带来的表单号与服务器端存储的表单号是否一致,一致则通过验证,否则禁止提交表单
		if(!client_token.equals(server_token)){
			return false;
		}
		//验证成功,返回true
		return true;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}


//3.在表单页面用javascript控制表单重复提交

<!DOCTYPE html>
<html>
  <head>
    <title>表单提交</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <script type="text/javascript">
       var flag=false;
       function onsubmit(){
          if(!flag){
             flag=true;
             return true;
          }else{
             return false;
          }
       }
   </script>
  </head>
  
  <body>
   <form action="/day06/servlet/LoginServlet" onsubmit ="return onsubmit();" method="post">
    用户名:<input name="username" type="text">
    <input type="submit" value="提交" id="submitInput">
    </form>
  <!-- onsubmit ="getElementById('submitInput').disabled=true;return true;" -->
  </body>
</html>


你可能感兴趣的:(JavaWeb防止表单重复提交)