Calling servlet from JSP [duplicate]
Basically, I want to display the products in an ArrayList on a JSP page. I have done that in the servlet code. But theres no output.
Also Do I have to place products.jsp in the /WEB-INF folder? When I do that, I get a requested not resource error.
My Servlet Code (InventoryServlet.java)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
List<Product> products = new ArrayList<Product>();
products = Inventory.populateProducts(); // Obtain all products.
request.setAttribute("products", products); // Store products in request scope.
request.getRequestDispatcher("/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (Exception ex) {
throw new ServletException("Retrieving products failed!", ex);
}
}
My JSP Page (products.jsp)
<h2>List of Products</h2>
<table>
<c:forEach items=开发者_开发问答"${products}" var="product">
<tr>
<td>${product.Description}</td>
<td>${product.UnitPrice}</td>
</tr>
</c:forEach>
</table>
Web.xml
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>Inventory</servlet-name>
<servlet-class>com.ShoppingCart.InventoryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Inventory</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
</web-app>
You need to open the page by requesting the servlet URL instead of the JSP URL. This will call the doGet()
method.
Placing JSP in /WEB-INF
effectively prevents the enduser from directly opening it without involvement of the doGet()
method of the servlet. Files in /WEB-INF
are namely not public accessible. So if the preprocessing of the servlet is mandatory, then you need to do so. Put the JSP in /WEB-INF
folder and change the requestdispatcher to point to it.
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
But you need to change all existing links to point to the servlet URL instead of the JSP URL.
See also:
- Servlets info page
Here is a diagram for web application folder structure. No need to place your JSPs under WEB-INF.
- debug or put print statememnts in your Servlet to make sure that the arraylist has elements in it.
- Right-click on your browser and view page source. Is there anything generated at all?
the difference between put a jsp file under WebRoot and WEB-INF is: if you put under WebRoot, user can access your jsp file using the URL on the address bar of browser; if you put under WEB-INF, user can't access the file because it is hidden from public.
The only way you can access that is through Servlet using forward or redirect.
精彩评论