webtier@glassfish.java.net

JSF 2.0: Handling Relative URLs in Facelets Templates

From: <webtier_at_javadesktop.org>
Date: Wed, 11 Nov 2009 11:16:59 PST

I am updating my Facelets page-templating mini-tutorial from JSF 1.x to JSF 2.0. In doing so, I am trying to figure out how to handle relative URLs.

The issue is that I have pages in different subfolders that use the same templates, so I have to make all of the URLs in those templates be relative to the context root (i.e., /myproj/images/foo.gif), so that they still resolve correctly. But, of course, I don't want to hardcode the context root, since it might change.

For style sheets, JavaScript files, and images, there is an easy solution: put the files under the "resources" folder and use h:outputStylesheet, h:outputScript, and h:graphicImage, each with a "library" attribute. This works well.

However, what about normal hypertext links? For example, suppose that several of the templates refer to "foo.jsf". Using a href="foo.jsf" or h:link value="foo.jsf" is obviously wrong because the files that use the templates might be in a subdirectory. But using a href="/myproj/foo.jsf" is also obviously wrong because the context root could change later. I couldn't find an option in h:link that said "make this relative to the context root".

I could easily define a bean that dynamically looks up the project root, then do a href="#{bean.contextRoot}/foo.jsf". Or, I could use a predefined variable: a href="#{facesContext.externalContext.requestContextPath}/foo.jsf". But these are long and a little bit hard to read. Since there is explicit support for handling relative URLs for images, style sheets, and JavaScript files, I figured I was missing something obvious for doing a similar trick for regular hypertext links.

Can anyone clue me in, please?

Cheers-
                                - Marty
                                
JSF 2.0 Tutorial: http://www.coreservlets.com/JSF-Tutorial/jsf2/
[Message sent by forum member 'martyhall' (hall_at_coreservlets.com)]

http://forums.java.net/jive/thread.jspa?messageID=371459