(...) 但我不想在 url 中显示 servlet 的名称。
在访问 Servlet 时,您根本不需要使用 Servlet 名称。事实上,您可以通过定义正确的 URL 模式来创建指向所需 URL 的 servlet:
@WebServlet("/index.jsp")
public class LatestProductServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
List<Product> productList = ...
//all the necessary code to obtain the list of products
//store it as request attribute
request.setAttribute("productList", productLlist);
//forward to the desired view
//this is the real JSP that has the content to display to user
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
}
然后,您将拥有这样的文件夹结构
- <root folder>
- WEB-INF
+ index.jsp
+ web.xml
在 WEB-INF/index.jsp 中:
<!DOCTYPE html>
<html lang="es">
<body>
<!--
Display the data accordingly.
Basic quick start example
-->
<c:forEach items="${productList}" var="product">
${product.name} <br />
</c:forEach>
</body>
</html>
请注意,您的客户将访问http://<yourWebServer>:<port>/<yourApplication>/index.jsp 并获得所需的内容。而且您不需要触发两个 GET 请求来检索特定页面的内容。
请注意,您可以使用这种方法走得更远:由于该模式现在在 servlet 中定义,您可以选择不为您的客户端使用 index.jsp,而是使用 index.html 来访问您的页面。只需更改 Servlet 中的 URL 模式:
@WebServlet("/index.html")
public class LatestProductServlet extends HttpServlet {
//implementation...
}
并且客户端将访问http://<yourWebServer>:<port>/<yourApplication>/index.html,这将在WEB-INF/index.jsp 中显示结果。现在您和您的客户都会很高兴:客户将获得他们的数据,而您不会在您的 URL 中显示那个丑陋的 servlet 名称。
附加
如果您将 index.jsp 作为 web.xml 中的欢迎页面,则此方法将不起作用,因为应用程序 servlet 期望存在一个真实文件 index.jsp。要解决这个问题,只需创建一个名为 index.jsp 的空文件:
- <root folder>
- index.jsp <-- fake empty file to trick the application server
- WEB-INF
+ index.jsp
+ web.xml
当访问http://<yourWebServer>:<port>/<yourApplication>/时,会如上图那样工作。