从JSP调用servlet [英] Calling servlet from JSP
问题描述
基本上,我想在JSP页面上的ArrayList中显示产品.我已经在servlet代码中做到了.但是没有输出.
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.
我还必须将products.jsp放在/WEB-INF文件夹中吗?当我这样做时,会收到请求的非资源错误.
Also Do I have to place products.jsp in the /WEB-INF folder? When I do that, I get a requested not resource error.
我的Servlet代码(InventoryServlet.java)
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);
}
}
我的JSP页面(products.jsp)
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>
推荐答案
您需要通过请求servlet URL而不是JSP URL来打开页面.这将调用doGet()
方法.
You need to open the page by requesting the servlet URL instead of the JSP URL. This will call the doGet()
method.
在/WEB-INF
中放置JSP可以有效地防止最终用户直接打开它,而无需使用servlet的doGet()
方法.即/WEB-INF
中的文件不可公共访问.因此,如果必须对Servlet进行预处理,则需要这样做.将JSP放在/WEB-INF
文件夹中,然后将requestdispatcher更改为指向它.
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);
但是您需要更改所有现有链接以指向servlet URL而不是JSP URL.
But you need to change all existing links to point to the servlet URL instead of the JSP URL.
这篇关于从JSP调用servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!