重定向解决浏览器刷新后数据多次存入的问题

当在浏览器提交表单, 提交成功后浏览器将跳转到一个新的html页面
提交成功后如果刷新页面
跳转方式如果是转发, 数据库将多存入数据一次原来数据

public class SaveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");

        // 获取表单提交的数据
        String usercode = request.getParameter("usercode");
        String username = request.getParameter("username");

        // JDBC
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true"
            , "root", "xxxxxx");
            conn.setAutoCommit(false);
            String sql = "insert into t_user(usercode, username) values (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, usercode);
            ps.setString(2, username);
            count = ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            System.out.println(count);
            if (count == 1) {
                // 保存成功
                // 跳转到成功页面
                // 转发
                request.getRequestDispatcher("/success.html").forward(request, response);
            }
        }

    }
}

如果采用重定向的方式将不会出现上面的问题
将if语句更改为如下

if (count == 1) {
        // 重定向
        response.sendRedirect(request.getContextPath() + "/success.html");
}

这是因为, 重定向之后, 浏览器两次请求, 最后一次请求时浏览器的地址为/success.html
此时刷新, 刷新的是/success页面, 而不是提交表单时候的页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值