标签:style blog http io ar color os sp for
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; } }
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/tplovejava/p/4164205.html