1. 程式人生 > >防止重複提交

防止重複提交

package web1;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TokenProcessor {

	private static final String TOKEN_KEY = "MENHLIFANG";

	private static final String TRANSACTION_TOKEN_KEY = "TRANSACTION_TOKEN_KEY";

	private static TokenProcessor instance = new TokenProcessor();

	private long previous;

	protected TokenProcessor() {
		super();
	}

	public static TokenProcessor getInstance() {
		return instance;
	}

	public synchronized boolean isTokenValid(HttpServletRequest request) {
		return this.isTokenValid(request, false);
	}

	public synchronized boolean isTokenValid(HttpServletRequest request,
			boolean reset) {
		/*reqeust.getSession(false)獲取session,如果session不存在,則返回null
			如果 專案中無法確定回話一定存在,最好用request.session(false);
		 * */
		HttpSession session = request.getSession(false);

		if (session == null) {
			return false;
		}

		String saved = (String) session.getAttribute(TRANSACTION_TOKEN_KEY);

		if (saved == null) {
			return false;
		}

		if (reset) {
			this.resetToken(request);
		}

		String token = request.getParameter(TOKEN_KEY);

		if (token == null) {
			return false;
		}

		return saved.equals(token);
	}

	public synchronized void resetToken(HttpServletRequest request) {
		HttpSession session = request.getSession(false);

		if (session == null) {
			return;
		}

		session.removeAttribute(TRANSACTION_TOKEN_KEY);
	}

	public synchronized String saveToken(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String token = generateToken(request);

		if (token != null) {
			session.setAttribute(TRANSACTION_TOKEN_KEY, token);
		}
		
		return token;
	}

	public synchronized String generateToken(HttpServletRequest request) {
		HttpSession session = request.getSession();

		return generateToken(session.getId());
	}

	public synchronized String generateToken(String id) {
		try {
			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.getBytes());
			md.update(now);

			return toHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	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();
	}
}
package web1;

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("/tokenvalue")
public class TokenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		HttpSession  session=request.getSession();
//		Object  token=session.getAttribute("token");
//		String  tokenvalue=request.getParameter("token");
//		System.out.println(token);
//		System.out.println(tokenvalue);
//		if(token!=null&& token.equals(tokenvalue)){
//			session.removeAttribute("token");
//		}else{
//			response.sendRedirect(request.getContextPath()+"/token/token.jsp");
//		    return;
//		}
		boolean  valid=TokenProcessor.getInstance().isTokenValid(request);
		if(valid){
			TokenProcessor.getInstance().resetToken(request);
		}else{
			response.sendRedirect(request.getContextPath()+"/token/token.jsp");
			return ;
		}
		String  name=request.getParameter("name");
		//訪問資料庫伺服器
		System.out.println("name"+name);
		request.getRequestDispatcher("/token/success.jsp").forward(request, response);
	}
//	  boolean   val=TokenProcessor.getInstance().isTokenValid(request);
//	  if(val){
//		  TokenProcessor.getInstance().resetToken(request);
//		  
//	  }else{
//		 response.sendRedirect(request.getContextPath()+"/token/token.jsp");
//	  return ;
//	  }
//	  String name=request.getParameter("name");
//    request.getRequestDispatcher(request.getContextPath()+"/token/success.jsp").forward(request,response);
}
<%@ 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>Insert title here</title>
</head>
<body>
     <font  color="red">
               <%=session.getAttribute("message")==null ? "":session.getAttribute("message") %>
    
    </font>
      <form action="<%= request.getContextPath()%>/checkCodeServlet"   method="post">
      name:<input type="text" name="name"/>
      checkCode:<input type="text" name="CHECK_CODE_PARAM_NAME"/>
      <img alt="" src="<%=request.getContextPath()%>/validateColorServlet"/>
        <input type="submit" value="Submit"/>
      </form>
      
   <%-- 
   
   <font color="red">
         <%=session.getAttribute("message")==null ? "":session.getAttribute("message") %>
      
      </font>
      <form action="<%=request.getContextPath()%>/checkcodeServlet" method="post">
       name:<input type="text" name="name"/>      
       checkCode=:<input type="text" name="CHECK_CODE_PARAM_NAME"/>
       <img alt="" src="<%=request.getContextPath()%>/validateColorServlet">
       <input type="submit" value="Submit"/>
      </form>
   --%>   
      
      
      
</body>
</html>