• HttpSession解决表单的重复提交


    1). 重复提交的情况: 

    ①. 在表单提交到一个 Servlet, 而 Servlet 又通过请求转发的方式响应一个 JSP(HTML) 页面,
    此时地址栏还保留着 Serlvet 的那个路径, 在响应页面点击 "刷新"
    ②. 在响应页面没有到达时重复点击 "提交按钮".
    ③. 点击 "返回", 再点击 "提交"

    2). 不是重复提交的情况:

    点击 "返回", "刷新" 原表单页面, 再 "提交"。

    3). 如何避免表单的重复提交:

    在表单中做一个标记, 提交到 Servlet 时, 检查标记是否存在且是否和预定义的标记一致, 若一致, 则受理请求,
    并销毁标记, 若不一致或没有标记, 则直接响应提示信息: "重复提交"

    ①.调用 RequestDispatcher.forward() 方法,浏览器所保留的URL 是先前的表单提交的 URL,此时点击”刷新”, 浏览器将再次提交用户先前输入的数据,引起重复提交;如果采用 HttpServletResponse.sendRedirct() 方法将客户端重定向到成功页面,将不会出现重复提交问题

    ②.利用Session对表单进行token标识

    1. 在原表单页面, 生成一个随机值 token
    2. 在原表单页面, 把 token 值放入 session 属性中
    3. 在原表单页面, 把 token 值放入到 隐藏域 中.
    4.  在目标的 Servlet 中: 获取 session 和 隐藏域 中的 token 值
    5.  比较两个值是否一致: 若一致, 受理请求, 且把 session 域中的 token 属性清除
    6. 若不一致, 则直接响应提示页面: "重复提交"

    表单页面

    <%@ page import="java.util.Date" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <%
        //随机生成一个标识
        String tokenValue = new Date().getTime()+"";
        session.setAttribute("token",tokenValue);
    %>
    <form action="<%=request.getContextPath()%>/tokenServlet" method="post">
        <input  type="hidden"  name="tokenValue" value=<%=tokenValue%> />
        Username:<input  type="text" name="username"/>
        <input type="submit" value="登录"/>
    </form>
    </body>
    </html>    

    TokenServlet.java

    package yang.mybatis.servlet.token;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    /**
     * Created by yangshijing on 2017/11/22 0022.
     */
    public class TokenServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //模仿后台延时
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            HttpSession session = request.getSession();
            //从Session域中获得标识
            String token = (String)session.getAttribute("token");
            //从表单隐藏域中获取token value
            String tokenValue = request.getParameter("tokenValue");
            //如果标识不为空且隐藏域中值和Session域中的值一致,则处理该表单请求
            if(token != null && tokenValue.equals(token)){
                session.removeAttribute("token");
            }else{
                response.sendRedirect(request.getContextPath()+"/jsp/token/token.jsp");
                return;
            }
            request.getRequestDispatcher("/jsp/token/success.jsp").forward(request,response);
        }
    }

     TokenProcessor.java

    用于管理表单标识号的工具类,它主要用于产生、比较和清除存储在当前用户Session中的表单标识号。为了保证表单标识号的唯一性,每次将当前SessionID和系统时间的组合值按MD5算法计算的结果作为表单标识号,并且将TokenProcessor类设计为单例类

    package yang.mybatis.servlet.token;
    
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    /**
     * Created by yangshijing on 2017/11/23 0023.
     */
    public class TokenProcessor {
        //表单隐藏域的name属性值
        private static final String TOKEN_KEY = "TOKEN_KEY";
        //Session域中的属性值
        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) {
            HttpSession session = request.getSession(false);
    
            if (session == null) {
                return false;
            }
            //从Session域中获取标识值
            String saved = (String) session.getAttribute(TRANSACTION_TOKEN_KEY);
    
            if (saved == null) {
                return false;
            }
    
            String token = request.getParameter(TOKEN_KEY);
    
            if (token == null) {
                return false;
            }
    
            return saved.equals(token);
        }
        //移除Session域中的token
        public synchronized void resetToken(HttpServletRequest request) {
            HttpSession session = request.getSession(false);
    
            if (session == null) {
                return;
            }
    
            session.removeAttribute(TRANSACTION_TOKEN_KEY);
        }
        //将token保存到Session域中并返回token
        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();
        }
    }

    重构的index.jsp

    <%@ page import="java.util.Date" %>
    <%@ page import="yang.mybatis.servlet.token.TokenProcessor" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <%--<%
        String tokenValue = new Date().getTime()+"";
        session.setAttribute("token",tokenValue);
    %>--%>
    <form action="<%=request.getContextPath()%>/tokenServlet" method="post">
        <input  type="hidden"  name="TOKEN_KEY" value=<%=TokenProcessor.getInstance().saveToken(request)%> />
        Username:<input  type="text" name="username"/>
        <input type="submit" value="登录"/>
    </form>
    </body>
    </html>

    重构的TokenServlet

    package yang.mybatis.servlet.token;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    /**
     * Created by yangshijing on 2017/11/22 0022.
     */
    public class TokenServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //模仿后台延时
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         /*   HttpSession session = request.getSession();
            //从Session域中获得标识
            String token = (String)session.getAttribute("token");
            //从表单隐藏域中获取token value
            String tokenValue = request.getParameter("tokenValue");
            //如果标识不为空且隐藏域中值和Session域中的值一致,则处理该表单请求
            if(token != null && tokenValue.equals(token)){
                session.removeAttribute("token");
            }else{
                response.sendRedirect(request.getContextPath()+"/jsp/token/token.jsp");
                return;
            }
            request.getRequestDispatcher("/jsp/token/success.jsp").forward(request,response);*/
            boolean tokenValid = TokenProcessor.getInstance().isTokenValid(request);
            //如果不是重复的表单请求,移除token并处理请求
            if(tokenValid){
                TokenProcessor.getInstance().resetToken(request);
            }else {
                //重复的表单请求,结束方法,并重定向到提示页面
                response.sendRedirect(request.getContextPath()+"/jsp/token/token.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath()+"/jsp/token/success.jsp");
        }
    }
  • 相关阅读:
    在DNN模块开发中使用jQuery
    在MSBuild.exe中使用条件编译(Conditional Compile)
    ASP.NET SQL 注入免费解决方案
    html+css做圆角表格
    [ASP]sitemap地图生成代码
    刺穿MYIE|24小时同一ip弹一次|无须body加载|精简代码
    用ASPJPEG组件制作图片的缩略图和加水印
    16个经典面试问题回答思路[求职者必看]
    一个26岁IT男人写在辞职后
    搜弧IT频道的幻灯片切换的特效源代码
  • 原文地址:https://www.cnblogs.com/realshijing/p/7882026.html
Copyright © 2020-2023  润新知