2016-04-22 48 views
0

我是JSP和Servlet的新手。我在JSP示例(register.jsp)中有一個表單,它幫助我將數據發送到Servlet以便將值插入數據庫。然而,在我插入成功後,如果我點擊與(register.jsp)相同的URL,它會重新提交我之前輸入到數據庫中的相同數據。我如何防止這種情況?下面是我的代碼Double Form Submission JSP Servlet

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); 

回答

0

你可以大概在一個普通的方法接收您的servlet請求。對於不同的HTTP請求,您應該使用override不同的方法。像:

//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); 
     }