0

在 JSF 应用程序中,我们有目录层次结构:

webapp
  xhtml
    login.xhtml
    main.xhtml
    search.xhtml
  css
    main.css
    extra.css
  js
    jquery.js

等等。servlet 映射是:

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

这工作正常,但我们的网络应用程序的 URL 如下所示:

http://localhost/myapp/xhtml/login.xhtml
http://localhost/myapp/xhtml/search.xhtml

我们希望通过删除/xhtml部分来获得更简单的 URL,即 http://localhost/myapp/login.xhtml

我找不到任何方法来实现这一点。有没有办法做到这一点<servlet-mapping>?我需要一些额外的框架吗?

4

1 回答 1

1

可以Filter. 无论是本土的还是第三方的,比如URLRewriteFilter。只需将其映射*.xhtml,然后转发到/xhtml/*.

就像是:

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

String ctx = request.getContextPath();
String uri = request.getRequestURI();
String viewId = uri.substring(ctx.length(), uri.length());

if (viewId.startsWith("/xhtml")) {
    // Redirect to URL without /xhtml (changes URL in browser address bar).
    response.setStatus(301);
    response.setHeader("Location", ctx + viewId.substring("/xhtml".length());
    // Don't use response.sendRedirect() as it does a temporary redirect (302).
} else {
    // Forward to the real location (doesn't change URL in browser address bar).
    request.getRequestDispatcher("/xhtml" + viewId).forward(request, response);
}

但更简单的方法是更改​​目录层次结构以摆脱/xhtml子文件夹。这些 CSS/JS(和图像)文件最好放在/resources子文件夹中,以便您可以以适当的方式利用<h:outputStylesheet>,<h:outputScript>的功能。<h:graphicImage>

也可以看看:

于 2011-12-21T13:05:00.000 回答