Architecture & DesignThe PrimeFaces UI Framework for Java EE

The PrimeFaces UI Framework for Java EE

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This article is dedicated to JSF developers who have never heard about PrimeFaces or never tried it in a real application. I’m sure that after we highlight the main advantages provided by PrimeFaces, you will want to join the great PrimeFaces community, and all your JSF production’s application will be developed under the PrimeFaces UIs umbrella. I know that it sounds like a too enthusiastic an introduction, but after you will read this article, you will feel the same.

In a simple but meaningful definition, PrimeFaces is a gold mine for JSF developers. Technically speaking, PrimeFaces is a comprehensive set of 100+ JSF UI components compatible with HTML5. Besides the great look and feel, PrimeFaces components support fine-grained AJAX capabilities, are responsive eligible, and are compatible with any modern browser and device (for example, from desktop to mobile devices). In addition, PrimeFaces comes with PrimeFaces PUSH (based on the Atmosphere framework), PrimeFaces Extensions, which is a lightweight open source component library for JSF 2.0.  Further, we have to mention the Prime UI, which is a spin-off from PrimeFaces and is a collection of rich JavaScript widgets based on the jQuery UI. Recently (January 11, 2016), PrimeUI 3.0 is available featuring PrimeElements, which is the WebComponents library to create user interfaces declaratively with custom HTML elements. Practically, PrimeElements is an add-on library for PrimeUI. And, let’s not forget the WIP project named Prime NG, which is a collection of rich UI components for AngularJS2. All these goodies were developed by the PrimeFaces team (leader Cagatay Civici) and are defined as the “Ultimate UI Framework for Java EE.”

And, if this information is not enough to make you curious about exploring the PrimeFaces world, maybe several testimonials and the list of PrimeFaces users will do it. Need even more? Well, how about PrimeFaces blog, events, training, forum, books, certification, and partners? Still more? How about PrimeFaces themes and astonishing layouts: Titan, Volt, Adamantium, Modena, Rio, Ronin, Spark and last (for the moment) Sentinel.

Please allow me to add my own testimonial here: My main area of expertise is focused on developing GIS RIA applications using Java EE technologies. These kinds of applications involve pretty rich GUIs and geographical maps. I remember that when I discovered PrimeFaces I was trying to find a set of components that will allow me to have a main layout (to place the map in the center), collapsible-expandable components, built-in upload for multiple files with progress bar, great look and feel and powerful AJAX capabilities for supporting RIA concept. Well, since then I’ve developed four such projects based on PrimeFaces, and you can see some screenshots here. So, a big thank you to the PrimeFaces team for developing this great library.

Well, I think that if you’ve read this far, I’ve got your attention.

It is time to have a closer look to what PrimeFaces can do for your JSF application. Of course, is impossible to cover everything in an article, but once you “taste” PrimeFaces via this article, you will run for more on PrimeFaces Showcase and PrimeFaces Manual.

Let’s get started our overview with PrimeFaces’ AJAX support.

Installing PrimeFaces

Installing PrimeFaces is very easy to accomplish. You can add PrimeFaces into a project as a JAR or as a Maven dependency:

<dependency>
   <groupId>org.primefaces</groupId>
   <artifactId>primefaces</artifactId>
   <version>5.3</version>
</dependency>

Setting a theme can be accomplished by following the instructions from here.

Brief Overview of PrimeFaces Components

If you are familiar with JSF, learning PrimeFaces will be like a walk in the park!

PrimeFaces AJAX Core

Face01
Figure 1: The AJAX core

One of the most powerful features of PrimeFaces consists of AJAX support for all its components. Because you are a JSF developer, you should be familiar with <f:ajax/>, but PrimeFaces comes with an improved version of this tag, named <p:ajax/>. The <p:ajax/> has the same core functionalities as <f:ajax/>; it allows us to indicate the components to process via process attribute (alias <f:ajax execute>) and the components to update via the update attribute (alias <f:ajax render>). In addition, <p:ajax/> is integrated with <p:ajaxStatus/> (this is a global and configurable indicator to provide feedback about the ongoing AJAX request), allows the use of callback parameters, uses jQuery for DOM manipulation, and supports the @parent keyword. Nevertheless, <p:ajax/> doesn’t accept children. Here it is a snippet of a call using <p:ajax/>:

<h:form>
   <p:inputText value="#{fooBean.fooValue}">
      <p:ajax event="fooEvent" update="fooId"
         listener="#{fooBean.fooListener}" />
   </p:inputText>
   <h:outputText id="fooId"
      value="#{fooBean.fooValue}" />
</h:form>

To provide feedback about the ongoing AJAX request, PrimeFaces comes with a Status component exposed via the <p:ajaxStatus/> tag. This component can be used with a facet-driven declarative approach or by using callbacks. This will work globally at view level, which means that any AJAX request in the page will be monitored by <p:ajaxStatus/>. For example, if you choose the facet-driven declarative approach, you can rely on this skeleton:

<p:ajaxStatus>
   <f:facet name="default">
      // a text or an image to be displayed by default
   </f:facet>

   <f:facet name="start">
      // a text or an image (animated GIF) to be displayed
      // during AJAX request processing
   </f:facet>

   <f:facet name="complete">
      // a text or an image to be displayed after the AJAX
      // request was processed
   </f:facet>
</p:ajaxStatus>

Or, if you rely on callbacks, you can easily shape a modal dialog to appear when an AJAX request is processed:

<p:ajaxStatus onstart="PF('fooDialog').show()"
              onsuccess="PF('fooDialog').hide()" />

<p:dialog widgetVar="'fooDialog'" modal="true"
             draggable="false"
          closable="false" resizable="false"
             showHeader="false">
   // add the dialog content here
</p:dialog>

This was just a small introduction in PrimeFaces AJAX Core. Via PrimeFaces Showcase you can explore more goodies, such as Poll, RemoteCommand, partial submit, and so forth.

PrimeFaces Input Components

Face02
Figure 2: The PrimeFaces input components

To collect data from the user, PrimeFaces comes with 25+ dedicated components. You think of an input component … and PrimeFaces has it!

We can say that in the first category of input components we have the components that exist in JSF also, such as <h:inputText/>, <h:selectManyCheckbox/>, <h:selectManyMenu/>, <h:inputTextarea/>, and so on. Each of these components has been improved by PrimeFaces and fortified with more features and attributes. For example, PrimeFaces InputText extends standard InputText with skinning capabilities, wheereas the PrimeFaces SelectManyMenu provides an advanced version of standard SelectManyMenu that allows us to display checkboxes, images, and the like in the list of items via <p:column/>. The PrimeFaces InputTextarea extends standard InputTextarea with autoComplete, autoResize, remaining characters counter, and theming features.

In the second category of input components, we have components that don’t exist in the JSF core; some of them doesn’t exist in other JSF extensions, either. These are mighty components and each of them is implemented as a high-performance server-side web UI component. For example, you need a cool calendar in your page? Just try the PrimeFaces Calendar component. Among others, you can choose between inline calendar:

<p:calendar id="inline" value="#{fooBean.fooDate}"
            mode="inline" />

a popup calendar:

<p:calendar id="popup" value="#{fooBean.fooDate}" />

only time selection:

<p:calendar id="time" value="#{fooBean.fooDate}"
            pattern="HH:mm" timeOnly="true" />

Or, maybe you need a good-looking rating component. How about PrimeFaces Rating component with callback, AJAX rate, and read-only capabilities? The following snippet of code will render a rating component with an AJAX rate:

<p:rating value="#{fooBean.fooRatingValue}">
   <p:ajax event="rate" listener="#{fooBean.onrate}"
      update="..." />
   <p:ajax event="cancel" listener="#{fooBean.oncancel}"
      update="..." />
</p:rating>

When browsing the consistent list of input components, do not hesitate to check out the AutoComplete, InputMask, Inplace, and InputNumber components.

PrimeFaces Button Components

Face03
Figure 3: The PrimeFaces button components

I’m sure that you already noticed the well-known Button, Link, CommandButton, and CommandLink components. PrimeFaces extends the JSF standard ones with AJAX, partial processing and skinning features. By default, a PrimeFaces command button/link will fire an AJAX POST request, and in order to obtain a non-AJAX POST request you need to explicitly set ajax="false". Here it is a simple PrimeFaces command button which will fire an AJAX request and will execute some JavaScript code at the end depending on the request status:

<p:commandButton value="Click Me!" action="#{fooBean.fooAction()}"
                 oncomplete="fooScript();"
                 onsuccess="buzzScript();"
                 onerror="bizzScript();"/>

Moreover, you may need a SplitButton which displays a default command and additional ones in an overlay. All these artifacts have access to fine-grained AJAX capabilities via attributes like process, update, partialSubmit, partialSubmitFilter, delay, and timeout.

Commonly, you will see usages as below (this button will submit the current form via AJAX request, will update the messages and will execute a piece of JavaScript (for example, display a dialog window) when the AJAX request completes):

<h:form>
   ...
   <p:messages id="fooId"/>
   ...

<p:commandButton value=”Click Me!” action=”#{fooBean.fooAction()}” update=”fooId” oncomplete=”fooScript();“/> … </h:form>

PrimeFaces Data Components

Face04
Figure 4: The PrimeFaces data components

PrimeFaces data components are another strong reason for using PrimeFaces. Here, we have a bunch of components capable of displaying and manipulating data. From the mighty DataTable to the “exotic” Ring, from the very useful PickList to the fun TagCloud, these components are really awesome. Practically, you can write a great book about only these components and name it something like PrimeFaces Data Processing UIs.

The DataTable component provided by PrimeFaces is a real deal and is very powerful compared to the JSF core data table. Tabular data are a very important aspect in Web applications and features such as pagination and lazy loading are always welcome. The complete list of DataTable features consists of: Basic, Facets, Paginator, Sort, Filter, Selection, Group, SubTable, SummaryRow, Expansion, Columns, Edit, Scroll, RowColor, Lazy, Resize, Reorder, ColToggler, ContextMenu, Sticky, Responsive, and RTL.

For example, a data table with pagination and lazy loading looks like this:

<p:dataTable var="t" value="#{fooBean.fooList}" rows="10"
             paginator="true"
             paginatorTemplate="{CurrentPageReport}
                {FirstPageLink} {PreviousPageLink}
                {PageLinks} {NextPageLink} {LastPageLink}
                {RowsPerPageDropdown}"
             rowsPerPageTemplate="5,10,15">
   <p:column headerText="Id">
      <h:outputText value="#{t.fooProperty}" />
   </p:column>
   ...
</p:dataTable>

Another popular data component is PickList. This is a dual list input component with Drag and Drop-based reordering, transition effects, theming filtering, captions, checkbox selection, client-server callbacks, responsive layout, and more. A simple PickList looks like the following:

<p:pickList id="fooId" value="#{fooBean.dualListModel}"
            var="t" itemLabel="#{t}" itemValue="#{t}" />

A PickList as you have never seen before has Pojo Support with Effect, Captions, Custom Content, Reordering, Filtering, Checkboxes, Ajax Events, and Responsive. Such an example is available on PrimeFaces Showcase.

Among other popular data components, we have: GMap, Tree, and DataExporter.

PrimeFaces Panel Components

Face05
Figure 5: The PrimeFaces panel components

There is no secret that JSF has a pretty limited offer of panels. Basically, we have the <h:panelGroup/>, which can be rendered as a <div/> or a <span/>, and the <h:panelGrid/>, which is rendered as an HTML table.

Compared to this offer, PrimeFaces provides a comprehensive suite of panels. Personally, I love to use the Layout panel in my JSF applications. You simply put the Layout in a page and start building your application interface in its panels. You can display all of its five panels, or only a sub-set of panels, and each panel excepting the center panel is closable and collapsible. Moreover, they are resizable and support a wide range of effects when they are collapsed/expanded. Following, you can see a skeleton code for a full page Layout:

<p:layout fullPage="true">
   <p:layoutUnit position="north" size="150" header="Top"
                 resizable="true" closable="true" collapsible="true">
      //page code
   </p:layoutUnit>

   <p:layoutUnit position="south" size="150" header="Bottom"
                 resizable="true" closable="true" collapsible="true">
      //page code
   </p:layoutUnit>

   <p:layoutUnit position="west" size="250" header="Left"
                 resizable="true" closable="true"
                 collapsible="true">
      //page code
   </p:layoutUnit>

   <p:layoutUnit position="east" size="250" header="Right"
                 resizable="true" closable="true"
                 collapsible="true" effect="drop">
      //page code
   </p:layoutUnit>

   <p:layoutUnit position="center">
      //page code
   </p:layoutUnit>
</p:layout>

The Accordion and Fieldset components are also among my favorites. Because they are toggleable, we can use them to manage the page space in an optimal approach. For example, the skeleton of an accordion with three tabs is:

<p:accordionPanel>
   <p:tab title="tab_1_Name">
      // tab content
   </p:tab>
   <p:tab title="tab_2_Name">
      // tab content
   </p:tab>
   <p:tab title="tab_3_Name">
      // tab content
   </p:tab>
</p:accordionPanel>

Whereas a togglable fieldset looks like this:

<p:fieldset legend="fieldset_legend" toggleable="true"
      toggleSpeed="miliseconds">
   // fieldset content
</p:fieldset>

There is even a panel named Dashboard. This component supports drag&drop-based content reordering similar to portal environments.

PrimeFaces Overlay Components

Face06
Figure 6: The PrimeFaces overlay components

PrimeFaces overlays are very useful to display dialogs (modals/non-modals), confirmation dialogs, display images, inline content, iframes, tooltips, and more. Typically, these kinds of artifacts are obtained via additional JavaScript libraries. With PrimeFaces, we have them out of the box.

Probably, Dialog is the most used overlay component, so let’s have a brief skeleton of how it is commonly used (I also like the LightBox demo):

<p:commandButton value="Show Dialog!" type="button"
   onclick="PF('fooWV').show();" />
...
<p:dialog header="fooHeader" widgetVar="fooWV"
          modal="true" >
   // dialog content
</p:dialog>

You may also be interested in Dialog Framework.

PrimeFaces Menu Components

Face07
Figure 7: The PrimeFaces menu components

Using menus in JSF is a real challenge. Practically, we don’t have any built-in component capable of rendering an HTML snippet of code that looks like a menu bar.

Well, PrimeFaces provides a pretty cool menu bar (Menubar) and much more. An interesting menu is the ContextMenu, which brings one of the most common desktop UIs into a JSF page. PrimeFaces allows us to attach the context menu to any component in page (tree, data table, and so forth).

Not all PrimeFaces menus are “sober.” Check out the funny Stack and Dock menus. You probably think that you need a complex piece of code to obtain a menu like Stack, but PrimeFaces simplifies this task so much that all you need is to follow this skeleton:

<p:stack icon="yourIconPath" expanded="true">
   <p:menuitem value="fooValue" icon="yourIconPath"
      url="#"/>
   <p:menuitem value="fooValue" icon="yourIconPath"
      url="#"/>
   <p:menuitem value="fooValue" icon="yourIconPath"
      url="#"/>
   ...
</p:stack>

Personally, I’ve used the SlideMenu several times in production; it displays nested submenus with a slide animation. This is a pretty cool menu because it occupies little space, has great slide animations, and looks great in an Accordion component.

PrimeFaces Charts Components

Face08
Figure 8: The PrimeFaces charts components

It is obvious that PrimeFaces has paid attention to charts. Most of the common charts types are available with zooming, animations, boundaries, and formatting capabilities.

They look very professional, they are interactive, can be updated in real time, support multi axes, can be exported as static images, can be combined, and are responsive. There is no need to rely on other charts libraries anymore.

Starting from the classical charts types like Line, Bar, and Area, continuing with the well-known Pie, Bubble, and MeterGauge, and ending with the Donut and OHLC. They are all great.

Especially for charting dates, PrimeFaces has the Date chart. Dates in charts are displayed by using the DateAxis API that provides special zooming, boundaries, and formatting capabilities.

For each type of chart, you have to provide the correct chart model and use <p:chart/>:

<p:chart type="line" model="#{fooBean.lineModel}"
         style="height:300px;"/>

The preceding lineModel should represent an instance of org.primefaces.model.chart.LineChartModel. More details about PrimeFaces chart models can be found on PrimeFaces Showcase and official documentation.

PrimeFaces Messages Components

Face09
Figure 9: The PrimeFaces messages components

As you know, JSF support four types of messages: info, error, warn, and fatal.

By default, these messages are rendered to the user via an HTML <ul/> list. On the other hand, PrimeFaces offers a stylized version that looks friendlier by signaling the message types via a meaningful colors and icons. Check a demo of Messages.

Beside Messages, PrimeFaces provides the possibility to display FacesMessages in a great looking and configurable overlay named Growl. This is typically configured as in the following skeleton:

<h:form>
   <p:growl id="fooId" showDetail="true" sticky="true" />

   // more content (inputs)

   <p:commandButton value="Submit"
                    actionListener="#{fooBean.fooAction()}"
                    update="fooId" />
</h:form>

If you want to style the Growl component, maybe this article will help you.

PrimeFaces Multimedia Components

Face10
Figure 10: The PrimeFaces multimedia components

Although the JSF core allows us to display images via <h:graphicImage/>, PrimeFaces allows us to do much more than that. We can display, compare, and crop images, play video content, and even to take photos with the webcam and send them to the backend model.

My favorite components from this category are the gallery component Galleria and the cross-browser generic player Media.

Basically, all components from this category save us a lot of work and time spent for developing or searching media components on the Internet. As long as you have the media content, simply pass it to the desired component and PrimeFaces will do the rest for you.

Check out how simple we can obtain an image compare application:

<p:imageCompare leftImage="left_image_path"
                rightImage="right_image_path"
                width="x" height="y"/>

There is also a Barcode component capable to generate various types of barcodes in PNG or SVG formats.

PrimeFaces File Components

Face11
Figure 11: The PrimeFaces file components

There are only two components under the File category, Upload and Download. The PrimeFaces Upload component looks great and works very well. I’ve tried it several times in production with 10+ files and up to 500MB and it worked as expected. Currently, PrimeFaces provides five types of upload: basic, single, multiple, auto, and drag&drop. Here it is a skeleton for multiple uploading:

<h:form>
   <p:fileUpload fileUploadListener="#{fooBean.fooHndleFileUpload}"
                 mode="advanced" dragDropSupport="false"
                 multiple="true" update="fooId"
                 sizeLimit="100000" fileLimit="3"
                 allowTypes="/(.|/)(gif|jpe?g|png)$/" />

   <p:growl id="fooId" showDetail="true" />
</h:form>

PrimeFaces DragDrop Components

Face12
Figure 12: The PrimeFaces DragDrop components

By using the <p:draggable/> tag, we can add drag&drop capability to a component. Basically, we need to refer the corresponding component via its client ID in the for attribute of the <p:draggable/> tag.

The DataTable and DataGrid components provide a data table; respectively, a data grid with drag and drop capabilities. Practically, you can drag the rows from a table; respectively, the items from a data grid into a droppable area.

In addition, PrimeFaces allows us to customize the drag&drop feature via JavaScript.

PrimeFaces Client Side Validation

Face13
Figure 13: The PrimeFaces client side valiation

Definitely, this is one of the most powerful feature of PrimeFaces. Validation is always an important aspect of an application and everybody wants it to take place quickly and securely, or … secure and quick. Obviously, this goal is pretty hard to achieve because fast takes place on the client-side, but is not that secure, whereas secure takes place on the server-side, but is not that fast. Well, PrimeFaces comes with the Client Side Validation Framework that implements JSF validation API within the browser. As the official Showcase points, this validation is characterized by the following aspects:

  • Compatible with Server Side Implementation
  • Conversion and Validation happens on the client side
  • Partial Processing support for AJAX
  • I18n support along with component specific messages
  • Client side Renderers for message components
  • Easy to write custom client converters and validators
  • Global- or Component-based enable/disable
  • Little footprint using HTML5
  • Advanced Bean Validation Integration

Personally, I like the Bean validation which is integrated with Bean Validation Specification, but I also like the Custom, which allows us to write a custom client converter or validator based on JSF and/or Bean Validation APIs. In this article, you can read about PrimeFaces’ cross-field client bean validation.

PrimeFaces Miscellaneous Components

Face14
Figure 14: The PrimeFaces miscellaneous components

A significant number of components that don’t fit in the preceding categories are available under the miscellaneous category.

Actually, here we have several great components, such as Captcha, RequestContext, ProgressBar, Responsive, and so on.

Obviously, you have to take your time and explore at least once each of these components. I’m sure that components such as Spotlight, BlockUI, or DefaultCommand already have captured your curiosity.

Well, that’s all, folks! I hope you enjoyed this article and PrimeFaces shortly will become your favorite JSF UI library. Currently, facts show that PrimeFaces is the leading JSF framework and it definitely deserves its place:

  • Number two at DevRates when this article was written, with 8.8 points.
  • PrimeFaces forum reaches 130,000+ posts and 60,000+ registered community members.
  • The most accessed components on JSF Showcase is the ZEEF page.

For those who also are fans of OmniFaces, you may be interested in the WIP book PrimeFaces & OmniFaces Powers Combined.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories