Using PrimeFaces to pimp up existing Java Server Faces / JSF 2 Applications

November 14th, 2010 by

In this tutorial we’re going to modify an existing Java Server Faces / JSF 2 web application by adding rich UI components to the existing layout.

Our tool of choice here is the PrimeFaces framework. It offers a wide range of interesting, customizable and (several) Ajax-enabled components that blend very well with JSF1+2  and also a solid documentation that allows a quick integration into existing projects.

 

Project setup

For this tutorial we’re going to reuse the web application from my JSF2 Tutorial “Java Server Faces/JSF 2 Tutorial – Step 1: Project setup, Maven and the first Facelet” – the source code is available at Bitbucket.org.

If you have Mercurial installed check it out using

hg clone http://bitbucket.org/hascode/hascode-tutorials

Now that we’ve got a running JSF2 web app lets start to add some shiny UI elements with PrimeFaces..

PrimeFaces Integration

Integrating PrimeFaces into your existing Java Server Faces application is quite easy and it takes only two steps if you’re using PrimeFaces >= 2.2 (thanks Cagatay Civici for mentioning!) ..

  1. Add the PrimeFaces Maven Repository to your pom.xml
    <repositories>
     [..]
     <repository>
      <id>prime-repo</id>
      <name>Prime Technology Maven Repository</name>
      <url>http://repository.primefaces.org</url>
      <layout>default</layout>
     </repository>
    </repositories>
  2. Add the following dependency to your pom.xml
    <dependency>
     <groupId>org.primefaces</groupId>
     <artifactId>primefaces</artifactId>
     <version>2.2.RC1</version>
    </dependency>
  3. If you’re using an older version of PrimeFaces (< 2.2) you have to edit your web.xml and add the following ResourceServlet and mapping
    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    <web-app>
     [..]
    	<servlet>
    		<servlet-name>Resource Servlet</servlet-name>
    		<servlet-class>org.primefaces.resource.ResourceServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>Resource Servlet</servlet-name>
    		<url-pattern>/primefaces_resource/*</url-pattern>
    	</servlet-mapping>
      [..]
    </web-app>

Using Mojarra we need to enable allowTextChildren so add the following context paremeter to your web.xml

<context-param>
 <param-name>com.sun.faces.allowTextChildren</param-name>
 <param-value>true</param-value>
</context-param>

The only dependency PrimeFaces itself needs is Java 5+ and a Java Server Faces 1.2+ implementation but some special components require additional dependencies. For more detailed information take a look at chapter “2.2 Dependencies” in the PrimeFaces Users Guide.

  • DataExporter Component: itext 1.4.8+ for PDF export support and apache poi 3.2-FINAL+ for Excel export support
  • FileUpload Component: commons-fileupload 1.2.1+ and commons-io 1.4+ for .. as you might have guessed .. file uploads ..
  • Ajax Push Component: atmosphere-runtime 0.5.1+ and atmosphere-compat 0.5.1+ for Ajax push

Integrate a component in a Facelet

Let’s pimp up the registration form with some nice UI elements. The PrimeFaces Showcase is good location for inspirations .. so let’s take a look what we could add to our layout :)

To use those UI elements in one of our facelets the only thing we need to add to our facelet is a new namespace to the html element

xmlns:p=”http://primefaces.prime.com.tr/ui”

Before we’re going to pimp up our registration form just keep the current “beautiful” layout in mind – that’s what our application currently looks like

  1. One of the first shiny elements on the show cases list is the new accordion panel .. we don’t need it but we’re going to integrate it! :) Change your registration.xhtml to this
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <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"
    	xmlns:p="http://primefaces.prime.com.tr/ui">
    <ui:composition template="/decorator.xhtml">
    	<ui:define name="title">hasCode.com - Java Server Faces Tutorial - Registration</ui:define>
    	<ui:define name="body">
    		<h:form>
    			<div id="registration"><p:accordionPanel autoHeight="false">
    				<p:tab title="Nickname">
    					<h:panelGrid columns="2" cellpadding="10">
    						<label>Nickname</label>
    						<h:inputText label="Nickname" id="nname"
    							value="#{userBean.nickname}" required="true" />
    						<h:message for="nname" />
    					</h:panelGrid>
    				</p:tab>
    				<p:tab title="E-Mail">
    					<h:panelGrid columns="2" cellpadding="10">
    						<label>E-Mail</label>
    						<h:inputText label="E-Mail" id="email" value="#{userBean.email}"
    							required="true" validator="#{userBean.validateEmail}" />
    						<h:message for="email" />
    					</h:panelGrid>
    				</p:tab>
    				<p:tab title="Birthday">
    					<h:panelGrid columns="2" cellpadding="10">
    						<label>Birthday</label>
    						<h:inputText label="Birthday" id="birthday"
    							value="#{userBean.birthday}" required="true">
    							<f:convertDateTime pattern="yyy-MM-dd" />
    						</h:inputText> (yyyy-mm-dd)
    					<h:message for="birthday" />
    					</h:panelGrid>
    				</p:tab>
    			</p:accordionPanel> <h:commandButton action="success" value="Register" /></div>
    			<h:messages />
    		</h:form>
    	</ui:define>
    </ui:composition>
    </html>

    Now our registration form looks like this

    For detailed information about the accordion widget take a  look at the accordion examples or the JavaDocs

  2. Entering date formats manually sucks .. that’s why we integrate a nice clickable calendar for the birthday .. we change the birthday panel in the registration.xhtml to this
    <p:tab title="Birthday">
     <h:panelGrid columns="2" cellpadding="10">
      <label>Birthday</label>
      <p:calendar value="#{userBean.birthday}" required="true" />
      <h:message for="birthday" />
     </h:panelGrid>
    </p:tab>

    Our calendar looks nice now

    For detailed information about the calendar widget take a  look at the calendar examples or its JavaDocs

  3. We haven’t changed the email entry field so let’s look what we can find for this one …
    Okayy .. what about autocompletion? ;)  Change the e-mail pannel according to this snippet

    <p:tab title="E-Mail">
     <h:panelGrid columns="2" cellpadding="10">
      <label>E-Mail</label>
      <p:autoComplete id="acSimple" value="#{userBean.email}"
       required="true" validator="#{userBean.validateEmail}"
       completeMethod="#{userBean.suggestEmail}" />
      <h:message for="email" />
     </h:panelGrid>
    </p:tab>

    Now we need to implement an example-like autocompletion method .. I have put it into the UserBean for convenience. It just reads the text from the user input and returns a list of e-mail addresses containing the entered text

    public List<String> suggestEmail(String entered) {
     List<String> list = new ArrayList<String>();
     for (int i = 1; i < 11; i++) {
      list.add(entered + i + "@hascode.com");
     }
     return list;
    }

    Our e-mail form looks like this now

    For detailed information about the autocomplete element take a look at its examples or its JavaDocs

  4. What to add next? We want to display an information if the user idles around on our registration form for more than five seconds .. this is where the IdleMonitor component comes into play. Just add the following code to your ui:define section
    <p:idleMonitor timeout="5000" onidle="idleWatcher.show();"
     onactive="idleWatcher.hide();" />
     
    <p:dialog header="Are you still there?" resizable="false"
     widgetVar="idleWatcher" modal="true" width="500" height="300">
     <h:outputText
      value="Please continue filling out the registration form." />
    </p:dialog>

    Refresh the registration form and don’t move your mouse or use the keyboard for five seconds and you will see the following screen

    Get more information about the IdleMonitor on its examples page or its JavaDocs

Skinning

All PrimeFaces UI elements are ThemeRoller compatible .. just add the ThemeSwitcher component to the registration form to play around with the different default skins. For more information about ThemeRoller and the jQuery UI CSS Framework take a look at the documentation.

<div id="registration">
<p:themeSwitcher initialText="Change Theme" buttonPreText="Theme: "/><br/>
[..]


Conclusion

We have added some nice and rich UI components in only a few steps and without major modifications in our managed beans or the runtime environment needed. To grab an interesting component from the Showcases Website and integrate them into an existing layout is made really easy and helpful documentation is also available.

In a real-world productive scenario we surely were forced to adjust the UI components according to a given/existing design and to deliberate about whether a component might harm the accessibility of the application.

Imho PrimeFaces is indeed a very nice addition to the JSF world and might save you some time and nerves when implementing special UI components.

If you need another example, please take a look at my article “Creating a sample Java EE 6 Blog Application with JPA, EJB, CDI, JSF and Primefaces on GlassFish”

If you want to see the web application in action, take a look at this screencast on YouTube.

Download Tutorial Sources

You may download the sources from Bitbucket.org or check them out via

hg clone http://bitbucket.org/hascode/hascode-tutorials

Resources

Article Updates

  • 2018-06-01: Embedded YouTube video removed (GDPR/DSGVO).

    Tags: , , , , , , , , , , ,

    3 Responses to “Using PrimeFaces to pimp up existing Java Server Faces / JSF 2 Applications”

    1. Cagatay Civici Says:

      Hi,

      Great article!

      Just a quick note, point 3 is not needed as of PrimeFaces 2.2, there is no need for any type of configuration.

    2. micha kops Says:

      Thanks for your remark! *article updated* :)

    3. Selin Says:

      Hi,

      Thanks for this article :)

    Search
    Categories