java_客户端防表单重复提交和服务器端session防表单重复提交
用户输入FormServlet链接
FormServlet-〉form.jsp->DoFormServlet
FormServlet:产生token,放在session中
form.jsp:hidden拿到token数据 并一同提交到>DoFormServlet
DoFormServlet:检测是否重复提交表单
//FormServlet
//产生表单 public class FormServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //产生随机数,表单号 TokenProcessor tp = TokenProcessor.getInstance(); String token = tp.generateToken(); request.getSession().setAttribute("token", token); request.getRequestDispatcher("/form.jsp").forward(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } //随机数发生器 class TokenProcessor{ private TokenProcessor(){} private static final TokenProcessor instance = new 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()); BASE64Encoder encode = new BASE64Encoder(); return encode.encode(md5); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block throw new RuntimeException(); } } }
//form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My jsp</title> </head> <body> <form action="/NANA/servlet/DoFormServlet" method="post"> <input type="hidden" name="token" value="${token}"> 用户名:<input type="text" name="username"><br/> <input type="submit" value="提交"> </form> </body> </html>
DoFormServlet:
public class DoFormServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean b = isTokenValid(request); if(!b){ System.out.println("submitted"); return; } request.getSession().removeAttribute("token"); System.out.println("success,insert user"); } private boolean isTokenValid(HttpServletRequest request) { // TODO Auto-generated method stub 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.equalsIgnoreCase(server_token)){ return false; } return true; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }