所以我有一個使用 Java 設定的“在線商店”,其中我有一個 .jsp“產品頁面”,其中顯示 8 種不同的產品。用戶可以單擊這些產品中的任何一個,然后被帶到該產品的另一個 .jsp 頁面。我有一個這樣設定的 servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get data from data class
ArrayList<Product> products = ProductData.getProduct();
//add products to request object
request.setAttribute("product-list", products);
//get requesr dispatcher
RequestDispatcher dispatcher = request.getRequestDispatcher("ProductPage.jsp");
//forward to jsp
dispatcher.forward(request, response);
}
到目前為止,我能夠在“產品頁面”上看到產品,但我現在正嘗試使用相同的 servlet 將相同的資訊也發送到 8 個單獨的產品頁面中的每一個。這可能嗎 ?或者我是否也需要為每個 jsp 頁面創建 8 個單獨的 servlet?
我知道可以使用會話,但為了節省解釋原因的時間,假設這個專案我不能使用會話。
謝謝!
uj5u.com熱心網友回復:
您不需要八個 servlet。一個ProductServlet應該就夠了。您只需要在您的 servlet 中有一些邏輯來轉到一個 JSP 或另一個。
您可以添加指向您的每個產品的ProductPage.jsp鏈接,這些鏈接可能鏈接到地址http://your.domain/yourServletMapping?productId=1, 或http://your.domain/yourServletMapping?productId=2, 等等。然后在您的 servlet 中,您只需要查看請求是否包含productId引數,然后您就知道必須顯示產品的詳細資訊頁面。您的代碼可能如下所示:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("productId") != null) {
// use the value from request.getParameter("productId") to get the ID of the product
int id = ...
// get the data from the data class for this product
Product product = ...
//add products to request object
request.setAttribute("product-details", product);
//get request dispatcher
request.getRequestDispatcher("ProductDetail.jsp").forward(request, response);
} else {
// we are not looking for a particular product, so list all products
// get data from data class
ArrayList<Product> products = ProductData.getProduct();
//add products to request object
request.setAttribute("product-list", products);
//get request dispatcher
request.getRequestDispatcher("ProductPage.jsp").forward(request, response);
}
}
您基本上需要根據某些引數的存在與否來區分請求,然后執行相應的邏輯。這就像您通過在 servlet 中使用兩種方法來處理它們來區分請求型別(GET 與 POST)一樣。
您還可以使用不同的 URL 來處理每種情況,例如http://your.domain/products列出產品http://your.domain/products/{productId},您可以映射到同一個 servlet 并從那里提取路徑引數,而不是請求引數。
如果事情變得更復雜,您也可以擁有多個 servlet,但考慮到您提出的問題很簡單,請盡量保持簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534337.html
上一篇:通過while回圈添加整數輸入
