【发布时间】:2022-12-17 20:38:44
【问题描述】:
有没有一种方法可以在不使用物理 url 链接的情况下将 servlet 链接到 JSP。所以我希望 servlet 运行,然后 servlet 将我带到 JSP。 有任何想法吗。
【问题讨论】:
有没有一种方法可以在不使用物理 url 链接的情况下将 servlet 链接到 JSP。所以我希望 servlet 运行,然后 servlet 将我带到 JSP。 有任何想法吗。
【问题讨论】:
只需调用 servlet 的 URL 而不是 JSP 的 URL,并在 servlet 的 doGet() 方法中执行预处理工作。
例如。在 JSP 显示产品之前加载产品列表的 servlet:
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
@EJB
private ProductService productService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: load list of products for display in JSP.
List<Product> products = productService.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
JSP 看起来像这样:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Our Products</title>
</head>
<body>
<h1>Products</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
如果您直接转到http://localhost:8080/contextname/products,那么将调用 servlet 的doGet(),产品将从数据库加载并存储在请求范围内,控制将转发给 JSP,JSP 又会以某种方式显示结果漂亮的 HTML 标记。
【讨论】:
是的,您可以在 servlet 中添加 html 代码,然后将重定向发送到 JSP 页面。
【讨论】:
是的,使用框架。单独使用 Servlet 和 JPS 就像水和石头——你可以用它们来修路,但你不能要求它们单独完成。你必须努力,或者得到一些框架来为你做这件事;)
如果您熟悉 Java,我建议 http://www.playframework.org/(1.2.4 ... 2.0 更少 Javish,更像 Scalish)
【讨论】:
我想你想要的是前锋。浏览器 URL 将维护 servlet 的 URL,请求中的属性将对 jsp 可用。
RequestDispatcher r = getServletContext().getRequestDispatcher("foo.jsp");
r.forward(请求,响应);
【讨论】: