我有一个 .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>
对于其他人,如果我有一个链接,例如:
<a href="/pages/page1.xhtml">Page 1</a>
我收到以下错误:
/page1.xhtml Not Found in ExternalContext as a Resource
我的问题是:如何在相对于 webapp 根目录的 href 中指定我想要的页面。
最佳答案
关于相对链接(即不以 http://开头的链接),您需要了解的两个主要事项:
- 以斜杠
/
开头的相对链接是相对于域根的。 - 不带前导斜线的相对链接是相对于请求 URL(就像在浏览器地址栏中一样)。
如果当前 URL 是 http://example.com/app并且该页面包含一个链接
<a href="/pages/page1.xhtml">
然后它将指向http://example.com/pages/page1.xhtml (失败)。
如果当前 URL 是 http://example.com/app并且该页面包含一个链接
<a href="pages/page1.xhtml">
然后它将指向http://example.com/app/pages/page1.xhtml (有效)。
如果当前 URL 是 http://example.com/app/pages/default.xhtml并且该页面包含一个链接
<a href="pages/page1.xhtml">
然后它将指向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">
因此,包括上下文路径,即 webapp 根目录。如果您唯一的问题是您想动态包含上下文路径,那么只需打印 HttpServletRequest#getContextPath()
<a href="#{request.contextPath}/pages/page1.xhtml">
另见:
关于web-applications - JSF:超链接到/webapp 子目录中的网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4853889/