从JSP调用servlet

use*_*636 3 java jsp servlets

基本上,我想在JSP页面上的ArrayList中显示产品.我在servlet代码中完成了这个.但是没有输出.

我还必须将products.jsp放在/ WEB-INF文件夹中吗?当我这样做时,我得到一个请求的不是资源错误.

我的Servlet代码(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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我的JSP页面(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>
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 10

您需要通过请求servlet URL而不是JSP URL来打开页面.这将调用该doGet()方法.

/WEB-INF有效地放置JSP 可以防止最终用户直接打开它而不涉及doGet()servlet 的方法.文件/WEB-INF不可公开访问.因此,如果servlet的预处理是强制性的,那么您需要这样做.将JSP放在/WEB-INF文件夹中并将requestdispatcher更改为指向它.

request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
Run Code Online (Sandbox Code Playgroud)

但是您需要将所有现有链接更改为指向servlet URL而不是JSP URL.

也可以看看:


rin*_*rer 5

这是Web应用程序文件夹结构的图表.无需将JSP放在WEB-INF下.

在此输入图像描述

  • 在您的Servlet中调试或放置print statememnts以确保arraylist中包含元素.
  • 右键单击浏览器并查看页面源.有没有产生任何东西?