JAVA Web防止表单重复提交实例

package com.it.java;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

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

//产生表单
@WebServlet(name="FormServlet",urlPatterns="/FormServlet")
public class FormServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //产生随机数  
    TokenProcessor tp = TokenProcessor.getInstance();
    String token = tp.generateToken();
    
    System.err.println("token----->"+token);

    request.getSession().setAttribute("token", token);
    request.getRequestDispatcher("/index.jsp").forward(request, response);

  }

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

}

//令牌  
class TokenProcessor {
  /* 
   * 1.把构造函数私有 
   * 2.自己创建一个 
   * 3.对外暴露一个方法,允许获取上面创建的对象 
   * */
  private static final TokenProcessor instance = new TokenProcessor();

  private TokenProcessor() {
  }

  public static TokenProcessor getInstance() {
    return instance;
  }

  public String generateToken() {
    String token = System.currentTimeMillis() + new Random().nextInt() + "";
    try {
      MessageDigest md = MessageDigest.getInstance("md5");
      byte[] md5 = md.digest(token.getBytes());
      //base64编码  
      BASE64Encoder encoder = new BASE64Encoder();

      return encoder.encode(md5);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自动生成捕捉块
      throw new RuntimeException(e);
    }
  }

}  



****************************************************

package com.it.java;

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 DoForm
 * 处理表单提交的请求
 */
@WebServlet(name="DoForm",urlPatterns="/DoForm")
public class DoForm extends HttpServlet {

  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userName = request.getParameter("userName");
    
    System.err.println("--------------------->>>"+userName);

//    try {
//      Thread.sleep(1000 * 3);
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    }

    boolean b = isTokenValid(request);

    if (!b) {
      System.err.println("请不要重复提交!");
      return;
    }
    request.getSession().removeAttribute("token");
    System.err.println("向数据库中注册用户==");
    
  }

  private boolean isTokenValid(HttpServletRequest request) {
    String client_token = request.getParameter("token");
    if (client_token == null) {
      return false;
    }
    String server_token = (String) request.getSession().getAttribute("token");
    if (server_token == null) {
      return false;
    }
    if (!client_token.equals(server_token)) {
      return false;
    }
    return true;
  }

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

}  



**************************************

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    String IPaddrs = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

    <title>测试</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">

    <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.11.1.min.js"></script>

    <script type="text/javascript">

        function submitTestFrom() {
            $.ajax({
                cache: true,
                type: "POST",
                url: "${pageContext.request.contextPath}/DoForm",
                data: $('#testFrom').serialize(),
                async: false,
                error: function (request) {
                    alert("Connection error");
                },
                success: function (data) {
                    alert("提交成功")
                }
            });
        }
    </script>

</head>

<body>
<form id="testFrom" name="testFrom" method="post">
    <input type="hidden" name="token" value="${token}">
    用户名:<input type="text" name="userName">
    <input type="button" value="提交" onclick="submitTestFrom()">
</form>
</body>
</html>  



你可能感兴趣的:(JAVA Web防止表单重复提交实例)