JAVA 重复提交

FormServlet

package servlet;

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 util.TokenProcessor;

/**
 * Servlet implementation class FormServlet
 */
public class FormServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = TokenProcessor.getInstance().makeToken();
        request.getSession().setAttribute("token", token);
        request.getRequestDispatcher("/form.jsp").forward(request, response);
    }

    
}

 

form.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form表单</title>
</head>

<body>
    <form action="${pageContext.request.contextPath}/DoFormServlet"
        method="post">
        <input type="hidden" name="token" value="${token}" /> 用户名:<input
            type="text" name="username"><input type="submit" value="提交">
    </form>
</body>
</html>

 

提交DoFormServlet

package servlet;

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;

public class DoFormServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public DoFormServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean b = isRepeatSubmit(request);
        if(b){
            System.out.println("请不要重复提交");
            return;
        }
         request.getSession().removeAttribute("token");//移除session中的token
        System.out.println("处理用户提交请求!!");
    }
    
    private boolean isRepeatSubmit(HttpServletRequest request){
        String client_token = request.getParameter("token");
        if(client_token == null){
            return true;
        }
        
        String server_token = (String) request.getSession().getAttribute("token");
        if(server_token == null){
            return true;
        }
        
        if(!client_token.equals(server_token)){
            return true;
        }
        
        return false;
    }

}

 

posted @ 2014-12-15 09:59  L_O_V_E_Java  阅读(253)  评论(0编辑  收藏  举报