在页面加载时从JSP文件调用servlet
我可以在不使用HTML表单的情况下从JSP文件调用servlet吗?
Can I call a servlet from JSP file without using a HTML form?
例如,在页面加载期间显示HTML表格中的数据库结果。
For example, to show results from database in a HTML table during page load.
你可以使用 doGet()
servlet方法预处理请求并将请求转发给JSP。然后在链接和浏览器地址栏中指向servlet URL而不是JSP URL。
You can use the doGet()
method of the servlet to preprocess a request and forward the request to the JSP. Then just point the servlet URL instead of JSP URL in links and browser address bar.
例如
@WebServlet("/products")
public class ProductsServlet extends HttpServlet {
@EJB
private ProductService productService;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
请注意,JSP文件放在 / WEB-INF $中c $ c>文件夹,防止用户直接访问它而不调用servlet。
Note that the JSP file is placed inside /WEB-INF
folder to prevent users from accessing it directly without calling the servlet.
另请注意 @WebServlet
仅在Servlet 3.0(Tomcat 7等)之后才可用,另请参阅使用Tomcat 7的@WebServlet注释。如果您无法升级,或者由于某种原因需要使用与Servlet 3.0不兼容的 web.xml
,那么您需要手动注册如下所示,在 web.xml
中使用旧式方法而不是使用注释:
Also note that @WebServlet
is only available since Servlet 3.0 (Tomcat 7, etc), see also @WebServlet annotation with Tomcat 7. If you can't upgrade, or when you for some reason need to use a web.xml
which is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xml
as below instead of using the annotation:
<servlet>
<servlet-name>productsServlet</servlet-name>
<servlet-class>com.example.ProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>productsServlet</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
一旦通过注释或XML正确注册了servlet,现在可以通过 http:// localhost:8080 / context / products 其中 / context
是webapp的已部署上下文路径, / products
是servlet的URL模式。如果你里面碰巧有任何HTML < form>
,那就让它POST到当前的网址,就像这样< form method =发布>
并添加 doPost()
到同一个servlet来执行后处理工作。继续以下链接,了解更具体的例子。
Once having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where /context
is the webapp's deployed context path and /products
is the servlet's URL pattern. If you happen to have any HTML <form>
inside it, then just let it POST to the current URL like so <form method="post">
and add a doPost()
to the very same servlet to perform the postprocessing job. Continue the below links for more concrete examples on that.
- Our Servlets wiki page
- doGet and doPost in Servlets
- How to avoid Java code in JSP
- Beginning and intermediate JSP/Servlet tutorials