How to reference CSS / JS / image resource in Facelets template?

JsfResourcesJsf 2FaceletsTemplating

Jsf Problem Overview


I've done tutorial about Facelets templating.

Now I've tried to create a page that isn't in same directory as the template. I've got problems with page style, because of styles are referenced with relative path like so:

<link rel="stylesheet" href="style_resource_path.css" />

I can use absolute referencing by starting with /:

<link rel="stylesheet" href="/project_root_path/style_resource_path.css" />

But this will bring me troubles when I'll be moving application to a different context.

So I'm wondering what is best way to reference CSS (and JS and image) resources in Facelets?

Jsf Solutions


Solution 1 - Jsf

##Introduction

The proper JSF 2.x way is using <h:outputStylesheet>, <h:outputScript> and <h:graphicImage> with a name referring the path relative to webapp's /resources folder. This way you don't need to worry about the context path as you would do in JSF 1.x. See also https://stackoverflow.com/questions/7162566/how-to-include-css-relative-to-context-path-in-xhtml-in-jsf-1-1

##Folder structure

Drop the CSS/JS/image files in /resources folder of the public webcontent as below (just create one if not already exist at the same level as /WEB-INF and /META-INF).

WebContent
 |-- resources
 |    |-- css
 |    |    |-- other.css
 |    |    `-- style.css
 |    |-- js
 |    |    `-- script.js
 |    `-- images
 |         |-- background.png
 |         |-- favicon.ico
 |         `-- logo.png
 |-- META-INF
 |    `-- MANIFEST.MF
 |-- WEB-INF
 |    |-- faces-config.xml
 |    `-- web.xml
 |-- page.xhtml
 :

In case of Maven, it should be in /main/webapp/resources and thus not /main/resources (those are for Java resources (properties/xml/text/config files) which must end up in runtime classpath, not in webcontent). See also https://stackoverflow.com/questions/13540907/maven-and-jsf-webapp-structure-where-exactly-to-put-jsf-resources.

##Referencing in Facelets

Ultimately, those resources are available as below everywhere without the need to fiddle with relative paths:

<h:head>
    ...
    <h:outputStylesheet name="css/style.css" />
    <h:outputScript name="js/script.js" />
</h:head>
<h:body>
    ...
    <h:graphicImage name="images/logo.png" />
    ...
</h:body>

The name attribute must represent the full path relative to the /resources folder. It does not need to start with /. You do not need the library attribute as long as you aren't developing a component library like PrimeFaces or a common module JAR file which is shared by multiple webapps.

You can reference the <h:outputStylesheet> anywhere, also in <ui:define> of template clients without the need for an additional <h:head>. It will via the <h:head> component of master template automatically end up in generated <head>.

<ui:define name="...">
    <h:outputStylesheet name="css/style.css" />
    ...
</ui:define>

You can reference <h:outputScript> also anywhere, but it will by default end up in the HTML exactly there where you declared it. If you want it to end up in <head> via <h:head>, then add target="head" attribute.

<ui:define name="...">
    <h:outputScript name="js/script.js" target="head" />
    ...
</ui:define>

Or, if you want it to end up at the end of <body> (right before </body>, so that e.g. window.onload and $(document).ready() etc isn't necessary) via <h:body>, then add target="body" attribute.

<ui:define name="...">
    <h:outputScript name="js/script.js" target="body" />
    ...
</ui:define>

##PrimeFaces HeadRenderer

In case you're using PrimeFaces, its HeadRenderer will messup the default <h:head> script ordering as described above. You're basically forced to force the order via PrimeFaces-specific <f:facet name="first|middle|last">, which may end up in messy and "untemplateable" code. You may want to turn off it as described in this answer.

##Packaging in JAR

You can even package the resources in a JAR file. See also https://stackoverflow.com/questions/8320486/structure-for-multiple-jsf-projects-with-shared-code.

##Referencing in EL

You can in EL use the #{resource} mapping to let JSF basically print a resource URL like /context/javax.faces.resource/folder/file.ext.xhtml?ln=library so that you could use it as e.g. CSS background image or favicon. Only requirement is that the CSS file itself should also be served as a JSF resource, otherwise EL expressions won't evaluate. See also https://stackoverflow.com/questions/6925733/how-to-reference-jsf-image-resource-as-css-background-image-url/6926193#6926193.

.some {
    background-image: url("#{resource['images/background.png']}");
}

Here's the @import example.

@import url("#{resource['css/other.css']}");

Here's the favicon example. See also https://stackoverflow.com/questions/5978684/jsf-add-favicon/5978920#5978920.

<link rel="shortcut icon" href="#{resource['images/favicon.ico']}" />

In case you're using a SCSS compiler (e.g. Sass Compiler Plugin for Maven), keep in mind that the SCSS processor might interpret # as a special character. In that case you would need to escape it with \.

.some {
    background-image: url("\#{resource['images/background.png']}");
}

##Referencing third-party CSS files

Third party CSS files loaded via <h:outputStylesheet> which in turn reference fonts and/or images may need to be altered to use #{resource} expressions as described in previous section, otherwise an UnmappedResourceHandler needs to be installed in order to be able to serve those using JSF. See also a.o. https://stackoverflow.com/questions/24666018/bootsfaces-page-shows-up-in-browser-without-any-styling and https://stackoverflow.com/questions/31434885/how-to-use-font-awesome-4-x-css-file-with-jsf-browser-cant-find-font-files/.

##Hiding in /WEB-INF

If you intend to hide the resources from public access by moving the whole /resources folder into /WEB-INF, then you can since JSF 2.2 optionally change the webcontent-relative path via a new web.xml context parameter as follows:

<context-param>
    <param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
    <param-value>/WEB-INF/resources</param-value>
</context-param>

In older JSF versions this is not possible.

###See also:

Solution 2 - Jsf

Suppose that you are running the in the sub directories of the web application. You may try like this :

 <link href="${facesContext.externalContext.requestContextPath}/css/style.css" rel="stylesheet" type="text/css"/>

The '${facesContext.externalContext.requestContextPath}/' link will help you to return immediately to the root of the context.

In relative URL's, the leading slash / points to the domain root. So if the JSF page is for example requested by http://example.com/context/page.jsf, the CSS URL will absolutely point to http://example.com/styles/decoration.css. To know the valid relative URL, you need to know the absolute URL of both the JSF page and the CSS file and extract the one from the other.

Let guess that your CSS file is actually located at http://example.com/context/styles/decoration.css, then you need to remove the leading slash so that it is relative to the current context (the one of the page.jsp):

<link rel="stylesheet" type="text/css" href="styles/decoration.css" />

Solution 3 - Jsf

These answers helped me to fix the same issue. Although my problem was more complex since I was using SASS and GULP.

I had to change (please note the "" in front of the #. Probably side effect from gulp:

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

 background: $blue url("\#{resource['my_theme/images/background-homepage-h1.png']}");

Solution 4 - Jsf

The resourcehandlers.UnmappedResourceHandler helps to map JSF resources on an URL pattern of /javax.faces.resource/*.

For me these 2 xml configs in faces-config.xml: org.omnifaces.resourcehandler.UnmappedResourceHandler

and in web.xml:

<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>/javax.faces.resource/*</url-pattern>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

helped with css and images.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkravemirView Question on Stackoverflow
Solution 1 - JsfBalusCView Answer on Stackoverflow
Solution 2 - JsfAbimaran KugathasanView Answer on Stackoverflow
Solution 3 - JsfMircea StanciuView Answer on Stackoverflow
Solution 4 - JsfBehruz ZaripovView Answer on Stackoverflow