In JSF 2.0, all your web resources files like css, images or JavaScript, should put in “resources” folder, under the root of your web application (same folder level with “WEB-INF“).

The sub-folder under “resources” folder is consider as “library” or “project theme“, later you can reference those “resources” with library attribute. This new JSF resources management mechanism is really useful, it allow developer to change the web resources easily by “theme/library” or “versioning”.

See below examples :

Figure 1-0 : Example of a JSF2 project folder structure.

jsf2 resources example

1. Normal Example

Here are some examples using “resources” and “library” in JSF 2.0.

  1. Include CSS file – h:outputStylesheet
    <h:outputStylesheet library="theme1" name="css/style.css" />

    HTML output…

    <link type="text/css" rel="stylesheet" 
       href="/JavaServerFaces/faces/javax.faces.resource/css/style.css?ln=theme1" />
  2. Display images – h:graphicImage
    <h:graphicImage library="theme1" name="img/sofa.png" />

    HTML output…

    <img src="/JavaServerFaces/faces/javax.faces.resource/img/sofa.png?ln=theme1" />
  3. Include JavaScript – h:outputScript

    <h:outputScript library="theme1" name="js/hello.js" />

    HTML output…

    <script type="text/javascript" 
       src="/JavaServerFaces/faces/javax.faces.resource/js/hello.js?ln=theme1">

2. Versioning Example

Refer to Figure 1-0, create a “version” folder matching regex \d+(_\d+)* under “library” folder, and the default JSF ResourceHandler will always get the highest version to display.

P.S Assume your project is Figure 1-0 structure

Include CSS file – h:outputStylesheet

<h:outputStylesheet library="default" name="css/style.css" />

Since “default” theme contains version “1_0” and “2_0“, JSF will always get the resources from the highest version, and append the version at the end of the resource.

See HTML output :

<link type="text/css" rel="stylesheet" 
   href="/JavaServerFaces/faces/javax.faces.resource/css/style.css?ln=default&amp;v=2_0" />
Version is optional
The version folder is optional, if you don’t have versioning, just omit it, like “newTheme” in Figure 1-0.

Thanks

Thanks BalusC for the comment, guide and correction, and sorry for my previous misleading guide.

References

  1. What is the JSF resource library for and how should it be used?
  2. JSF ResourceHandler JavaDoc
  3. JSF 2.0 New Feature Preview Series (Part 2.1): Resources
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to the charity, thanks.

Related Posts

Popular Posts