【问题标题】:In JSF, can I suppress part of the directory hierarchy of an XHTML file in the URL?在 JSF 中,我可以抑制 URL 中 XHTML 文件的部分目录层次结构吗?
【发布时间】:2011-12-21 11:26:01
【问题描述】:

在 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

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

【问题讨论】:

    标签: java jsf web-applications servlets url-mapping


    【解决方案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 子文件夹中,以便您可以适当地利用 &lt;h:outputStylesheet&gt;&lt;h:outputScript&gt;&lt;h:graphicImage&gt; 的功能。

    另见:

    【讨论】:

    • 感谢您的详细回复。很高兴知道我可以使用过滤器,但如果推荐的方法是将 XHTML 直接放入 webapp/,我想这就是我们要做的。没必要把事情复杂化...
    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2012-11-13
    • 2020-02-20
    • 2017-06-23
    • 2019-06-15
    • 1970-01-01
    • 2018-08-08
    • 2012-09-19
    相关资源
    最近更新 更多