JSF Resource Folder

Created: 28.07.2014

JSF 2.x includes a mechanism to link, versionize and protect resources like css and javascript files as well as images. Of course you cannot protect the files once they are transfered to the client, but you can restrict access to older versions and config files.

Set the Resource Folder in the web.xml

Assume there is a RegistrationHandler to register new users in a (very) simple web application:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ResourceExample</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <context-param>
	  <param-name>
	    javax.faces.WEBAPP_RESOURCES_DIRECTORY
	  </param-name>
	  <param-value>/META-INF/resources</param-value>
  </context-param>
</web-app>

Add Resources to the Directory

Now you can add resources to the specified directory:

Optionally you can manage versions of your libraries. To do so, add a parent folder with the pattern number_number, for example: "1_0".

Now, for instance, a css file can be linked like this:

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
	<h:outputStylesheet library="css" name="styles.css" />
	<title>FacesMessage</title>
</h:head>
<h:body>
<div style="width:500px;">
	<div class="errorMessageBox">Formatted by CSS</div>
</div>
</h:body>
</html>