过滤器防止重复提交

java过滤器代码
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * @author tai.tan
 * 用来处理重复提交过滤器
 */
public class DuplicataSubmitFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest servletrequest = (HttpServletRequest) request;
		HttpServletResponse servletresponse = (HttpServletResponse) response;
		String clientToken = servletrequest.getParameter("token");//获取页面token值
		//页面token值为空就不用过滤
		if(clientToken==null){
			arg2.doFilter(request, response);
		}else{
			HttpSession session = servletrequest.getSession();
			String sessionToken = (String) session.getAttribute("token");//获取会话token值
			//判断页面token值是否等于会话token值,会话token值为空就是第一次提交,相等就是重复提交
			if (sessionToken != null && clientToken.equals(sessionToken)) {
				servletresponse.setContentType("text/html");
				servletresponse.setCharacterEncoding("GBK");
				//跳转到错误提示页面
				servletresponse.sendRedirect(servletrequest.getContextPath()+"/public/duplicataSubmitError.jsp");
			}else{
				session.setAttribute("token", clientToken);//把页面token值赋予会话token值
				arg2.doFilter(request, response);	
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}

在jsp的form里面添加
<input type="hidden" name="token" value="<%=System.currentTimeMillis()%>" />

你可能感兴趣的:(重复提交)