您可以使用doGet() http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doGet%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29Servlet 的方法预处理请求并将请求转发到 JSP。然后只需在链接和浏览器地址栏中指向 servlet URL 而不是 JSP URL。
E.g.
@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
文件夹以防止用户在不调用 servlet 的情况下直接访问它。
另请注意@WebServlet
仅自 Servlet 3.0(Tomcat 7 等)起可用,另请参阅Tomcat 7 的 @WebServlet 注释 https://stackoverflow.com/questions/6535676/webservlet-annotation-with-tomcat-7。如果您无法升级,或者由于某种原因需要使用web.xml
它与 Servlet 3.0 不兼容,那么您需要以老式方式手动注册 servletweb.xml
如下而不是使用注释:
<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
是 web 应用程序的部署上下文路径/products
是 servlet 的 URL 模式。如果您碰巧有任何 HTML<form>
在其中,然后让它像这样 POST 到当前 URL<form method="post">
并添加一个doPost() http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doPost%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29到同一个 servlet 来执行后处理作业。继续以下链接以获取更多具体示例。
See also
- 我们的 Servlet wiki 页面 https://stackoverflow.com/tags/servlets/info
- Servlet 中的 doGet 和 doPost https://stackoverflow.com/questions/2349633/doget-and-dopost-in-servlets
- 如何避免在 JSP 中使用 Java 代码 https://stackoverflow.com/questions/3177733/howto-avoid-java-code-in-jsp-files
- Servlet 返回“HTTP 状态 404 请求的资源 (/servlet) 不可用” https://stackoverflow.com/questions/11731377/servlet-returns-http-status-404-the-requested-resource-servlet-is-not-availa