双表单提交JSP Servlet

时间:2016-04-22 13:47:04

标签: jsp servlets

我是JSP和Servlet的新手。我在JSP示例(register.jsp)中有一个表单,它帮助我将数据发送到Servlet以便将值插入数据库。但是,在我成功插入之后,如果我点击与(register.jsp)相同的URL,它会重新提交我之前在数据库中输入的相同数据。我该如何防止这种情况?以下是我的代码

JSP

  <form action="ServletComment" method="post" class="form-inline" role="form">
        <div class="form-group">
            <input class="form-control" type="text" placeholder="Your comments" name="userComment" />
             <input type="hidden" name="Action" value="updateComment" />
        </div>
        <div class="form-group">
            <button class="btn btn-default"> Add</button>
        </div>
    </form>

Servlet

String checkComment = null;
    checkComment = request.getParameter("Action");

    if(checkComment.equals("updateComment"))
    {
        // my coding
    }

request.getRequestDispatcher("/register.jsp").forward(request,response);  

1 个答案:

答案 0 :(得分:0)

您可能会在servlet中以常用方式接收请求。对于不同的override请求,您应HTTP使用不同的方法。像:

    //here only http get request will go in this method
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //do whatever you want
        }


    //here only http post request will go in this method    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String checkComment = null;
            checkComment = request.getParameter("Action");

            if(checkComment.equals("updateComment"))
             {
                // my coding
             }

            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }