POST請求我有以下幾點:Servlet的取消刷新
- JSP頁面提交請求到Servlet來添加新客戶
- 的Servlet使用了一些動作類
- 重定向到一些其他的Jsp頁面
這裏是源代碼。
new_customer.jsp:
<form action="/NewCustomerServlet" method="post">
<input type="test" name="company_name" />
<input type="submit" name="save_button" value="Save"/>
</form>
NewCustomerServlet:
@Override
protected void doPost(HttpServletRequest request, response) throws ServletException, IOException {
if(request.getParameter("save_button") != null){
Customer customer;
try {
customer = action.createCustomer(request, response);
request.setAttribute(Const.CUSTOMER, customer);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp?v=v_cst");
dispatcher.forward(request, response);
return;
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
request.setAttribute(Const.ERR_MSG_ATTR_NAME, "Failed to insert new customer: " +
e.getMessage());
RequestDispatcher dispatcher = request.getRequestDispatcher("CRM/index.jsp?v=n_cst");
dispatcher.forward(request, response);
return;
}
}
的index.jsp:
<%
if(request.getParameter("v").equals("v_cst")) {%>
<jsp:include page="customer/view_customer.jsp"></jsp:include>
<%} %>
view_customer.jsp:
<%
Customer customer = (Customer)request.getAttribute(Const.CUSTOMER);
String customerId = "";
String name = "";
String phone = "";
String website = "";
String address = "";
if(customer != null){
customerId = customer.getCustomerId();
name = customer.getName();
phone = customer.getPhone();
website = customer.getWebsite();
address = customer.getAddress();
}
%>
<table>
<tr>
<td>
<label>Customer ID</label>
</td>
<td>
<input type="text" name="customer_id" value="<%=customerId %>" />
</td>
<td>
<input type="button" value="Search" onclick="javascript:searchCustomer"/>
</td>
<td>
<label name="search_customer_err_msg" value="" style="color: red;"></label>
</td>
</tr>
<tr>
<td>
<label>Customer Name</label>
</td>
<td>
<input type="text" name="customer_name" value="<%= name%>"/>
</td>
</tr>
<tr>
<td>
<label>Customer website</label>
</td>
<td>
<input type="text" name="customer_website" value="<%= website%>" />
</td>
</tr>
<tr>
<td>
<label>Customer phone</label>
</td>
<td>
<input type="text" name="customer_phone" value="<%= phone%>"/>
</td>
</tr>
<tr>
<td>
<label>Customer Address</label>
</td>
<td>
<input type="text" name="customer_address" value="<%= address%>"/>
</td>
</tr>
</table>
從頁面new_customer.jsp增加一個新客戶,並查看頁面view_customer.jsp在瀏覽器中,如果我刷新頁面(從那裏我看到view_customer頁面後.jsp),它會再次將數據提交給servlet並添加一個新客戶,我將看到具有新客戶ID的相同數據。
也許我還應該提及,我在瀏覽器地址欄中看到NewCustomerServlet
的URL,而不是索引頁。
任何人都知道我在這裏錯過了什麼,以便在刷新時再次取消帖子?
**也許我忘了提及new_customer.jsp也包含在index.jsp頁面中,也許這可能是此行爲的原因?
您正在查看view_customer.jsp頁面上的數據,並且只有一個按鈕(搜索)。然後,它如何提交new_customer.jsp頁面提交按鈕。那麼new_customer.jsp是單獨的頁面還是包含在其他頁面中? –
感謝您的回答,因爲您可以在索引中注意到。jsp代碼我包括view_customer頁面 –
也許我忘了提及new_customer.jsp也包含在index.jsp頁面,也許這可能是這種行爲的原因? –