JSF: Hyperlink to webpage in /webapp subdirectory
I have a list of .xhtml pages that I keep in my /src/main/webapp/pages/ folder. Now I want to create hyperlinks to them. Currently the only one that works is the default home page: /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>
For the others, if I have a link such as:
<a href="/pages/page1.xhtml">Page 1</a>
I get the following error:
开发者_StackOverflow社区/page1.xhtml Not Found in ExternalContext as a Resource
My question is: How do I specify the page I want in a href relative to the webapp root.
Two major things you need to know about relative links (i.e. the ones not starting with http://):
- Relative links starting with a leading slash
/
are relative to the domain root. - Relative links without a leading slash are relative to request URL (as it is in browser address bar).
If the current URL is http://example.com/app and the page contains a link
<a href="/pages/page1.xhtml">
then it will point to http://example.com/pages/page1.xhtml (fails).
If the current URL is http://example.com/app and the page contains a link
<a href="pages/page1.xhtml">
then it will point to http://example.com/app/pages/page1.xhtml (works).
If the current URL is http://example.com/app/pages/default.xhtml and the page contains a link
<a href="pages/page1.xhtml">
then it will point to http://example.com/app/pages/pages/page1.xhtml (fails).
Your problem is that the welcome page is opened by a forward rather than a redirect. This way the request URL as it is in browser address bar stays on http://example.com/app while it is actually displaying the content of http://example.com/app/pages/default.xhtml. To get the links to work in all circumstances you want a link like
<a href="/app/pages/page1.xhtml">
Thus, including the context path, which is the webapp root. If your sole problem is that you want to include the context path dynamically, then just print HttpServletRequest#getContextPath()
<a href="#{request.contextPath}/pages/page1.xhtml">
See also:
- How to use relative paths without including the context root name?
精彩评论