首页 > 代码库 > session ---- 防止表单重复提交

session ---- 防止表单重复提交

技术分享

 

 

1.

package cn.itcast.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 sun.misc.BASE64Encoder;

//程序导向到表单, 产生表单号
public class FormServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//产生随机数 表单号
		TokenProcessor processor = TokenProcessor.getInstance();
		String token = processor.generateToken();
		request.getSession().setAttribute("token", token);//带给前台form并为以后校验用,所以要存session
		
		request.getRequestDispatcher("/form.jsp").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}

class TokenProcessor{//令牌发生器,产生唯一表单号用,单例
	
	private TokenProcessor(){}
	
	private static final TokenProcessor instance = new TokenProcessor();
	
	public static TokenProcessor getInstance(){
		return instance;
	}
	
	public String generateToken(){ //指纹摘要算法
		//121212  1231646466 4654646464646646 长度可能不一致,但我们需要长度一致
		String token = System.currentTimeMillis() + new Random().nextInt() + "";
		
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("md5");
			byte[] md5 = md.digest(token.getBytes()); //返回的是128位的指纹
			//String pass = new String(md5); 乱码, 用base64算法返回的是明文字符串即键盘能看到的
			//base64 把任意3个字节24个二进制位变成4个字节(6位/字节),但一个字节默认是8位,前面补00,
			//网络上的数据传递一般都是通过base64转过去传递
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
			
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	
	
}

  2.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://www.mamicode.com/">
    
    <title>My JSP </title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
	<form action="DoFormServlet" method="post">
		<input type="hidden" name="token" value=http://www.mamicode.com/${token} >"text" name="username">
		<input type="submit" value="http://www.mamicode.com/jsp表单提交">
	</form>
  </body>
</html>

  3.

package cn.itcast.form;


import java.io.IOException;

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

public class DoFormServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String username = request.getParameter("username");
		
		//模拟网络延迟
		/*try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("向数据库中注册用户..." + username);*/
		
		boolean flag = isTokenValid(request);
		if(!flag){ // 令牌无效,不准进入数据库! 
			System.out.println("请不要重复提交");
			return;
		}
		//todo 提交表单后的操作...
		request.getSession().removeAttribute("token");
		System.out.println("向数据库中注册用户..." + username);
	}
	
	//判断表单号是否有效, 闯过3关就是君子!
	private boolean isTokenValid(HttpServletRequest request) {
		String clientToken = request.getParameter("token"); 
		if(clientToken == null) { //坏人自己写表单提交
			return false;
		}
		
		String serveToken = (String) request.getSession().getAttribute("token");
		if(serveToken == null) { //上次提交过,服务端已经清除了token
			return false;
		}
		
		if(! clientToken.equals(serveToken)){
			return false;
		}
		
		return true;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}

  

session ---- 防止表单重复提交