JSF:/ webapp子目录中的网页超链接

Ste*_*eve 2 directory jsf web-applications hyperlink

我有一个.xhtml页面列表,我保存在/ src/main/webapp/pages /文件夹中.现在我想创建它们的超链接.目前唯一有效的是默认主页:/src/main/webapp/pages/default.xhtml.

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>/pages/default.xhtml</welcome-file>
  </welcome-file-list>

  <!-- JSF mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map these files with JSF -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

对于其他人,如果我有一个链接,如:

<a href="/pages/page1.xhtml">Page 1</a>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

在ExternalContext中找不到/page1.xhtml作为资源

我的问题是:如何在相对于webapp根目录的href中指定我想要的页面.

Bal*_*usC 9

关于相对链接需要了解的两个主要事项(即不以http://开头的那些):

  • /以前导斜杠开头的相对链接相对于域根.
  • 没有前导斜杠的相对链接与请求URL相关(因为它位于浏览器地址栏中).

如果当前网址为http://example.com/app且该网页包含链接

<a href="/pages/page1.xhtml">
Run Code Online (Sandbox Code Playgroud)

然后它会指向http://example.com/pages/page1.xhtml(失败).


如果当前网址为http://example.com/app且该网页包含链接

<a href="pages/page1.xhtml">
Run Code Online (Sandbox Code Playgroud)

然后它会指向http://example.com/app/pages/page1.xhtml(有效).


如果当前网址为http://example.com/app/pages/default.xhtml,则该网页包含链接

<a href="pages/page1.xhtml">
Run Code Online (Sandbox Code Playgroud)

然后它会指向http://example.com/app/pages/pages/page1.xhtml(失败).


您的问题是欢迎页面是由转发而不是重定向打开的.这样,浏览器地址栏中的请求URL保留在http://example.com/app上,而实际上显示的是http://example.com/app/pages/default.xhtml的内容.要使链接在所有情况下都能正常工作,您需要一个类似的链接

<a href="/app/pages/page1.xhtml">
Run Code Online (Sandbox Code Playgroud)

因此,包括上下文路径,即webapp根.如果您唯一的问题是您想要动态包含上下文路径,那么只需打印即可HttpServletRequest#getContextPath()

<a href="#{request.contextPath}/pages/page1.xhtml">
Run Code Online (Sandbox Code Playgroud)

也可以看看: