javaee 04 表单重复提交

@WebServlet("/login")
public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet.doGet()");
        req.getRequestDispatcher("/WEB-INF/views/Login.jsp").forward(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet.doPost()");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        
        String username = req.getParameter("usernmae");
        System.out.println("向数据库中插入数据 -->" + username);
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="/login" method="post">
        用户名:<input type="text" name="usernmae" id="usernmae" value="" />
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

当在页面中点击提交之后


image.png

image.png

情况1 此时按下F5


image.png

image.png

会重复去数据库中插入数据,这肯定不行

情况2


image.png

较为常用的解决方案
使用JavaScript 来解决这种问题

提交后禁用按钮


image.png
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript">
            $(function(){
                //点击按钮之后,只让提交一次
                $("#subBtn").click(function(){
                    $("#addForm").submit();
                    //提交之后将按钮禁用,随便点,反正也提交不上去
                    $("#subBtn").attr("disabled",true);
                });
            });
</script>

通过标识符,让按钮只能点击一次

    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            //标识符
            var status = false;

            $("#subBtn").click(function() {

                if (status == false) {
                    $("#addForm").submit();
                    //更改标识符,这样点了之后因为标识符不等于false,将不会提交表单
                    status = true;
                }
            });
        });
    </script>

使用session 来解决这个问题

1.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容