JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

PrimeFaces 5 Features

June 10, 2014 by Amr Mohammed Leave a Comment

This tutorial highlights the new features added as part of the PrimeFaces 5 release. PrimeFaces 5 has been announced and shipped with set of new components. We’ve published set of tutorials that covered the PrimeFaces 4 earlier in our blog. To summarize, PrimeFaces 5 comes up with set of new components and lot of minor enhancements in the framework.  At the end of this tutorial, I have uploaded the source code for this tutorial. You can download that and try the PrimeFaces 5 features in your environment. PrimeFaces 5 is compatible to JSF 2.0, JSF 2.1 and JSF 2.2. If you have any questions, please write it in the comments section.

The following are the new components added as part of the new release.

  1. DataScroller
  2. Cache
  3. Spotlight
  4. ColumnToggler
  5. ContentFlow

If you are not familiar with the PrimeFaces framework or JSF, please read the list of articles suggested below to get basic idea of the frameworks.

  • Introduction to JSF
  • Setting Up JSF Web Application Using Maven

The prerequisite or knowledge for this tutorial,

  • Java Server Faces (JSF) concepts
  • PrimeFaces
  • EclipseLink / JPA (This requires to display the data from the database)

Lets look at the examples.

1. DataScroller

DataScroller displays a collection of data with on demand loading using scrolling.

1.1 DataScroller Basic Info

DataScroller - Basic Info

1.2 DataScroller Attributes

DataScroller - Attributes

  1. DataScroller requires a collection of data to display, when the page is scrolled down, datascroller will do a request with ajax to fetch the new chunk of data and append them at the bottom.
  2. Defaulted scroll mode is the document, thus, the scrolling against page is monitored by the DataScroller component and at every time you get reached into the bottom of the page, an ajax request has been initiated cause data fetching with the same amount that you’ve specified in the chunkSize.
  3. The other applicable value for the mode attribute is inline which cause scrolling event be applied against the DataScroller itself.

1.3 DataScroller Demo

Here is the implementation for the DataScroller component. Lets look at the details of the implementation. Here I have listed the primefaces view and JSF managed bean.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces 5 New Components !</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<p:dataScroller value="#{registrationManagedBean.employees}" var="employee" chunkSize="10" mode="inline" scrollHeight="80">
<f:facet name="header">
Employees
</f:facet>
<f:facet name="loader">
<p:commandButton value="Scroll Down to Load More Employees" type="button"></p:commandButton>
</f:facet>
<h:panelGrid columns="2" style="width:100%" columnClasses="logo,detail">
<p:outputPanel>
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="#{employee.employeeName}" style="font-weight: bold"/>
</h:panelGrid>
</p:outputPanel>
</h:panelGrid>
</p:dataScroller>
</div>
</h:form>
</f:view>
</html>
[/code]

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory("persistenceUnit");
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ "unchecked"})
@PostConstruct
public void fetchEmployees() {
for (int i = 1; i < 100; i++) {
Employee emp = new Employee();
emp.setEmployeeName("Employee" + i);
emp.getAddress().setAddressCountry("Address" + i);
emp.getAddress().setAddressCity("Address" + i);
this.service.getTransaction().begin();
this.service.persist(emp);
this.service.getTransaction().commit();
emp = new Employee();
}
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
}

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

@SuppressWarnings("unchecked")
public String register() {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
this.employee = new Employee();
return "";
}
}
[/code]

  • Scrolling mode is inline, so the scrolling listener would be against the DataScroller itself.
  • ScrollHeight attribute is set to be 80, so that two employees should be shown. You will be able of scrolling down until you’ve finished the first chunk of data which is 10 employees as we’ve specified in the chunkSize.
  • Once we’ve reached into the last employee in the already first fetched chunk, an Ajax request has been initiated for fetching the next chunk of data and so on.
  • For simplifying the concept, we’ve used the loader facet which would be shown at every time you’ve finished scrolling of data chunk.
  • Once you’ve pressed on the button an Ajax loader image will be shown.
  • By eliminating the loader button, the chunk of data should be fetched when reaching into bottom while scrolling.

DataScroller - First Chunk

DataScroller - Fetch Second Chunk

DataScroller - Second Chunk Fetched

2. Cache

Cache component is used to reduce page load time by caching the content after initial rendering. It is one of the useful component added as part of the PrimeFaces 5 release.

2.1 Cache Basic Info

Cache Basic Info

2.2 Cache Attributes

Cache Attributes

2.3 Cache Demo

A cache store is required to use the cache component, two different providers are supported as cache implementations are EHCache and Hazelcast. Selected provider should be configured in the web.xml via a context-param.

Also there are few more steps required for configuring an EHCache. Defining cache regions are supported by using the cache tag which contains set of attributes used for defining the all required aspects of caching mechanism.

The Wiring of cache component with the cache mechanism that defined in the ehcache.xml is done via mentioning the cache name inside the XML in the region attribute for the cache component.

Once the page is loaded initially, content inside p:cache component is cached inside the cache region of the cache provider. Postbacks on the same page or reopening the page will retrieve the output from cache instead of rendering the content regularly.

The demonstration below shows you the impact of using the cache component into resolving the #{registrationManagedBean.employees} where the invocation of getEmployees() should be processed while the invocation isn’t Postback. After that every invocation is loaded from the cache.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Cache</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<p:cache region="cache" key="dataScrollerKey">
<p:dataScroller value="#{registrationManagedBean.employees}" var="employee" chunkSize="10" mode="inline" scrollHeight="80">
<f:facet name="header">
Employees
</f:facet>
<f:facet name="loader">
<p:commandButton value="Scroll Down to Load More Employees" type="button"></p:commandButton>
</f:facet>
<h:panelGrid columns="2" style="width:100%" columnClasses="logo,detail">
<p:outputPanel>
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="#{employee.employeeName}" style="font-weight: bold"/>
</h:panelGrid>
</p:outputPanel>
</h:panelGrid>
</p:dataScroller>
</p:cache>
</div>
</h:form>
</f:view>
</html>
[/code]

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory("persistenceUnit");
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ "unchecked"})
@PostConstruct
public void fetchEmployees() {
for (int i = 1; i < 100; i++) {
Employee emp = new Employee();
emp.setEmployeeName("Employee" + i);
emp.getAddress().setAddressCountry("Address" + i);
emp.getAddress().setAddressCity("Address" + i);
this.service.getTransaction().begin();
this.service.persist(emp);
this.service.getTransaction().commit();
emp = new Employee();
}
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
}

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List<Employee> getEmployees() {
if(FacesContext.getCurrentInstance().isPostback()){
System.out.println(":: Postpack invocation :: Employees List is loaded from the cache ::");
}
else {
System.out.println(":: Initial Invocation :: Employees List is loaded and returned ::");
}
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

@SuppressWarnings("unchecked")
public String register() {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
this.employee = new Employee();
return "";
}
}
[/code]

ehcache.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="cache" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
[/code]

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="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_2_5.xsd"
id="WebApp_ID" metadata-complete="true" version="2.5">
<context-param>
<description>State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>primefaces.CACHE_PROVIDER</param-name>
<param-value>org.primefaces.cache.EHCacheProvider</param-value>
</context-param>
<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>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
[/code]

pom.xml (Maven Build)

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>next.javabeat.jsf</groupId>
<artifactId>JavaBeat-Primefaces-JPA</artifactId>
<packaging>war</packaging>
<version>1.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<junit.version>4.9</junit.version>
<slf4j.version>1.6.4</slf4j.version>
<logback.version>1.0.1</logback.version>
<log4j.version>1.2.14</log4j.version>

<servlet.version>2.5</servlet.version>
<jsp.version>2.1</jsp.version>
<jstl.version>1.2</jstl.version>
<taglibs-standard.version>1.1.2</taglibs-standard.version>

<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>
<!– Servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!– Faces Implementation –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!– Faces Library –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!– Primefaces Version 5 –>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0.RC2</version>
</dependency>
<!– JSP Library –>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!– JSTL Library –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!– Google List Library –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<!– Dependencies for Eclipse JPA Persistence API –>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!– Dependency for ehcache provider –>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
</dependencies>

</project>
[/code]

Cache - Demo

  • Even we’ve provided a message print when the request become Postback, but it’s not shown.
  • The second Postback request is processed by the cache, thus the message of Postback in the getEmployees() hasn’t invoked.
  • Initial invocation has been displayed three times, cause nature of JSF lifecycle.

3. Spotlight

Spotlight highlights a certain component on page.

3.1 Spotlight Basic Info

Spotlight Basic Info

3.2 Spotlight Attributes

Spotlight Attributes

3.3 Spotlight Demo

Spotlight component is accessed by using the client side API. Before registration of new employee, nothing shown at all. Once Register action has been activated by clicking , an employees Table got highlighted for a while and all components are disabled except that highlighted one. Once the action has been returned and Register method finished, the highlight is never seen and everything got be normal again.
index.hxtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Cache</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false" onclick="PF(‘spot’).show()"/>
<p:spotlight target="dataScroller" widgetVar="spot"></p:spotlight>
<p:separator/>
<p:dataScroller id="dataScroller" value="#{registrationManagedBean.employees}" var="employee" chunkSize="10" mode="inline" scrollHeight="80">
<f:facet name="header">
Employees
</f:facet>
<f:facet name="loader">
<p:commandButton value="Scroll Down to Load More Employees" type="button"></p:commandButton>
</f:facet>
<h:panelGrid columns="2" style="width:100%" columnClasses="logo,detail">
<p:outputPanel>
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="#{employee.employeeName}" style="font-weight: bold"/>
</h:panelGrid>
</p:outputPanel>
</h:panelGrid>
</p:dataScroller>
</div>
</h:form>
</f:view>
</html>
[/code]

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory("persistenceUnit");
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ "unchecked"})
@PostConstruct
public void fetchEmployees() {
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
}

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List<Employee> getEmployees() {
if(FacesContext.getCurrentInstance().isPostback()){
System.out.println(":: Postpack invocation :: Employees List is loaded from the cache ::");
}
else {
System.out.println(":: Initial Invocation :: Employees List is loaded and returned ::");
}
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

@SuppressWarnings("unchecked")
public String register() throws InterruptedException {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery("select e from Employee e").getResultList());
Thread.currentThread().sleep(800);
this.employee = new Employee();
return "";
}
}
[/code]

Before Highlighting Employees Table

After Highlighting Employees Table

Employee Registration Had Finished

4. ColumnToggler

Visibility of dataTable columns can be controlled through using of column Toggler component. Regardless of the location that you’ve positioned column Toggler component inside your Table, either inside the head of the table or in one of those columns you’ve defined.

Once you’ve trigger the toggler by clicking on the trigger itself (which might be command button) a list of all dataTable columns become seen for your visibility control. Just check those columns you would see and uncheck those you wouldn’t.

ColumnToggler component has provided two mandatory attributes you must define when it comes to be used.

  • Datasource (Table) in which the ColumnToggler component will get the columns ready for being controlled and the trigger by which the toggler get displayed for controlling.
  • The remaining attributes are just normal ones, id, binding and rendered.

Toggler Displaying Controls

Toggler Controlling Columns

As you’ve seen, by toggling the dataTable columns above, you are able to seeing/hiding what you want of those columns in a fancy, easy-peasy way. Look below at the implementation required for Primefaces view where the managed bean isn’t changed.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Column Toggler</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<p:dataTable id="employeesSource" value="#{registrationManagedBean.employees}" var="employee">
<f:facet name="header">
Employees
<p:commandButton id="toggler" type="button" value="Columns" style="float:right" icon="ui-icon-calculator" />
<p:columnToggler datasource="employeesSource" trigger="toggler" />
</f:facet>
<p:column>
<f:facet name="header">
<p:outputLabel value="Employee Id"></p:outputLabel>
</f:facet>
<p:outputLabel value="#{employee.employeeId}"></p:outputLabel>
</p:column>
<p:column>
<f:facet name="header">
<p:outputLabel value="Employee Name"></p:outputLabel>
</f:facet>
<p:outputLabel value="#{employee.employeeName}"></p:outputLabel>
</p:column>
<p:column>
<f:facet name="header">
<p:outputLabel value="Employee’s Address Country"></p:outputLabel>
</f:facet>
<p:outputLabel value="#{employee.address.addressCountry}"></p:outputLabel>
</p:column>
<p:column>
<f:facet name="header">
<p:outputLabel value="Employee’s Address City"></p:outputLabel>
</f:facet>
<p:outputLabel value="#{employee.address.addressCity}"></p:outputLabel>
</p:column>
</p:dataTable>
</div>
</h:form>
</f:view>
</html>
[/code]

5. Content Flow

Content flow is a horizontal content gallery component with a slide animation.

5.1 Content Flow Basic Info

ContentFlow - Basic Info

5.2 Content Flow Attributes

ContentFlow - Attributes

5.3 Content Flow Demo

ContentFlow requires content as children that can either be defined dynamically using iteration or one by one. Each item must have the content style class applied as well.

indexContentFlow.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + ContentFlow</h2>
<p:outputPanel style="width: 700px;border: 1px;border-style: dotted;">
<p:contentFlow id="contentFlow" value="#{imageView.images}" var="image">
<h:graphicImage url="/resources/images/Image-#{image}.jpg" styleClass="content"></h:graphicImage>
</p:contentFlow>
</p:outputPanel>
</h:form>
</f:view>
</html>
[/code]

ImageView.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class ImageView {
private List<String> images = new ArrayList<String>();

public ImageView(){
this.images.add("1");
this.images.add("2");
}

public List<String> getImages() {
return images;
}

public void setImages(List<String> images) {
this.images = images;
}
}
[/code]

PrimeFaces 5 Project Structure

ContentFlow - Project Structure - Images Location

ContentFlow Demo

6. Persistence Entities

As per our explanation, we’ve introduced a JPA operations in our examples. These operations are done by a JPA entities and those entities are:

Address.java

[code lang=”java”]
package net.javabeat.jpa.data;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name = "address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer addressId;
private String addressCountry = "";
private String addressCity = "";

@OneToOne(cascade = CascadeType.ALL, mappedBy = "address")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer addressId) {
this.addressId = addressId;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.jpa.data;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address = new Address();

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
[/code]

7. Known issue

As you’ve seen, Primefaces content flow component doesn’t work for versions 5.0, 5.0.RC1, 5.0.RC2. We’ve opened a case at the Primefaces forums and this tutorial will be updated accordingly to the forum post.

8. Summary

Primefaces is one of the popular library for implementing JavaServer Faces UI. This tutorial has discussed most of the components introduced as part of the PrimeFaces 5. DataScroller, Cache, Spotlight, ColumnToggler and ContentFlow providing you a additional features in for UI design that your application may need.

Download Source Code for PrimeFaces 5

[wpdm_file id=113]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces Charts – Pie Chart + Ajax Behavior Events Example

April 24, 2014 by Amr Mohammed Leave a Comment

ItemSelect is one and only ajax behavior event of charts, this event is triggered when a series of a chart is clicked. In case you have listener defined, it’ll be executed by passing an org.primefaces.event.ItemSelectEvent instance. This tutorial has added a listener on that RegistrationBean that already exposed in the Primefaces Pie tutorial.

The listener that being added should list the users that belong to the selected category once the user has selected a colored pie.

1. The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Pie Chart + Ajax Behavior </h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Full Name:"/>
<p:inputText value="#{registerationBean.user.fullName}"/>
<h:outputText value="Enter Age:"/>
<p:inputText value="#{registerationBean.user.age}"/>
<h:outputText value="Enter Status [Example A, B, C or D]:"/>
<p:inputText value="#{registerationBean.user.status}"/>
<h:outputText value="Enter Address"/>
<p:inputText value="#{registerationBean.user.address.addressValue}"/>
</h:panelGrid>
<h:panelGrid columns="1">
<p:pieChart value="#{registerationBean.model}" legendPosition="w">
<p:ajax event="itemSelect" listener="#{registerationBean.listener}" process="@this" update="dataTable"></p:ajax>
</p:pieChart>
</h:panelGrid>
<h:commandButton value="Save User" action="#{registerationBean.saveUser}"/>
<br/>
<br/>
<br/>
<p:dataTable id="dataTable" value="#{registerationBean.selectedUsers}" var="user" border="1">
<p:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{user.fullName}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Status"/>
</f:facet>
<h:outputText value="#{user.status}"/>
</p:column>
</p:dataTable>
</h:form>
</f:view>
</html>
[/code]

2. The Managed Bean

RegistrationBean.java

[code lang=”java”]
package net.javabeat.primefaces.presenation;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import net.javabeat.eclipselink.persistence.data.User;

import org.primefaces.event.ItemSelectEvent;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean
@SessionScoped
public class RegisterationBean {
static EntityManagerFactory factory = null;
static EntityManager em = null;

static {
factory = Persistence.createEntityManagerFactory("mongoPU");
em = factory.createEntityManager();
}

private User user = new User();
private PieChartModel model = new PieChartModel();
private List<User> selectedUsers = new ArrayList<User>();

int aCounter = 0;
int bCounter = 0;
int cCounter = 0;
int dCounter = 0;

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

public List<User> getSelectedUsers() {
return selectedUsers;
}

public void setSelectedUsers(List<User> selectedUsers) {
this.selectedUsers = selectedUsers;
}

@SuppressWarnings("unchecked")
public PieChartModel getModel() {

// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u");
// Fetch the all users
List<User> users = query.getResultList();
// Categorize Users
for(User u : users){
if(u.getStatus().equals("A")){
aCounter++;
}
if(u.getStatus().equals("B")){
bCounter++;
}
if(u.getStatus().equals("C")){
cCounter++;
}
if(u.getStatus().equals("D")){
dCounter++;
}
}
this.model = new PieChartModel();
// Fill the model
model.set("A", aCounter);
model.set("B", bCounter);
model.set("C", cCounter);
model.set("D", dCounter);
return model;
}

public void setModel(PieChartModel model) {
this.model = model;
}

public String saveUser(){
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
this.user = new User();
return "";
}

public void listener(ItemSelectEvent e){
// Rest selected users
this.selectedUsers = new ArrayList<User>();
// A category has been selected
if(e.getItemIndex() == 0){
// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u WHERE u.status = ‘A’");
// Fetch the all users
this.selectedUsers = query.getResultList();
}
// B category has been selected
else if(e.getItemIndex() == 1){
// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u WHERE u.status = ‘B’");
// Fetch the all users
this.selectedUsers = query.getResultList();
}
// C category has been selected
else if(e.getItemIndex() == 2){
// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u WHERE u.status = ‘C’");
// Fetch the all users
this.selectedUsers = query.getResultList();
}
// D category has been selected
else if(e.getItemIndex() == 3){
// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u WHERE u.status = ‘D’");
// Fetch the all users
this.selectedUsers = query.getResultList();
}
}
}
[/code]

3. PrimeFaces Charts – Pie Chart + Ajax Behavior Example Demo

The below snapshot shows you the impact of using Ajax Behavior itemSelect for rendering the users that belong to a certain category.

PrimeFaces Charts - Pie Chart + Ajax Behavior Example Demo

[wpdm_file id=78]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces + EclipseLink / JPA + MongoDB Integration

April 22, 2014 by Amr Mohammed Leave a Comment

This tutorial explains the PrimeFaces + JPA + MongoDD integration. We are going to create a Pie Chart application using the PrimeFaces component library with the additional software JPA and MongoDB for the persistence mechanism. Before writing any snippet of code, you should have a proper installation and configuration for both the database (MongoDB) and the EclipseLink JPA/NOSQL persistence layer.

  • Also Read : PrimeFaces Tutorials

Tutorial Tools

  • Mongo Database 2.6
  • Eclipselink JPA/NOSQL 2.5.0
  • PrimeFaces 4.0
  • Apache Tomcat Server 7.0.35
  • Windows 7

MongoDB Installation & Configuration

In our previous article, we have explained How To Install MongoDB on Windows. If you have not installed MongoDB, please follow that article and setup the MongoDB in your system

See the below figures that shows you a proper running MongoDB and an open connection using the command line.

Running Mongo

  • The above figure shows you the result in of executing mongod.exe command.

Connect Mongo

  • The above screen shows you the result of executing monog.exe command.

Maven has provided the library for connecting the MONGODB by adding the following dependency. Add the maven for Mongo Java Driver dependency.

Maven For Mongo Database Java Driver

[code lang=”xml”]
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.4</version>
</dependency>
[/code]

EclipseLink JPA/NOSQL Installation & Configuration

We have discussed before EclipseLink library that responsible for connecting upon Relational Database at the EclipseLink – JPA Tutorial. But for connecting a non-relational databases such MongoDB – Document Based – you have to consider the EclipseLink JPA/NOSQL library.

The installation and configuration of that library needs Maven configurations, so It is worth for you to have a look at the EclipseLink – JPA Tutorial that mentioned above for seeing the way that how could maven being used for that purpose. The following coming few lines assumes that you are aware about installing and configuring the EclipseLink using maven.

For installing and configuring the EclipseLink – JPA/NOSQL you have to follow the below steps:

  • Add the required entries for EclipseLink – JPA/NOSQL maven repositories and dependencies.
  • Create your business domain (Classes).
  • Type the persistence.xml with the required domain classes and properties for the database being connected.

Maven EclipseLink – JPA/NoSQL Repositories

[code lang=”xml”]
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
<repository>
<id>EclipseLink</id>
<url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
</repository>
</repositories>
[/code]

Maven Eclipselink – JPA/NoSQL Dependencies

[code lang=”xml”]
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.nosql</artifactId>
<version>2.4.2-SNAPSHOT</version>
</dependency>
[/code]

Business Domain

For being this tutorial have a high intensity of concepts and snippet of codes, we’ve introduced a simple business domain for good understanding. The suggested domain contains of two classes, User and Address represent the domain where the User class has an association for Address.
User.java

[code lang=”java”]
package net.javabeat.eclipselink.persistence.data;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.eclipse.persistence.nosql.annotations.DataFormatType;
import org.eclipse.persistence.nosql.annotations.Field;
import org.eclipse.persistence.nosql.annotations.NoSql;

@Entity
@NoSql(dataFormat=DataFormatType.MAPPED)
public class User {
@Id
@GeneratedValue
@Field(name="_id")
private String id;
@Field(name="USERID")
private String userId;
@Field(name="fullName")
private String fullName;
@Field(name="AGE")
private String age;
@Field(name="STATUS")
private String status;
@Embedded
private Address address = new Address();

public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}

public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
[/code]

Address.java

[code lang=”java”]
package net.javabeat.eclipselink.persistence.data;

import javax.persistence.Embeddable;

import org.eclipse.persistence.nosql.annotations.DataFormatType;
import org.eclipse.persistence.nosql.annotations.Field;
import org.eclipse.persistence.nosql.annotations.NoSql;

@Embeddable
@NoSql(dataFormat=DataFormatType.MAPPED)
public class Address {
@Field(name="addressId")
private String addressId = "";
@Field(name="addressValue")
private String addressValue = "";

public String getAddressId() {
return addressId;
}
public void setAddressId(String addressId) {
this.addressId = addressId;
}
public String getAddressValue() {
return addressValue;
}
public void setAddressValue(String addressValue) {
this.addressValue = addressValue;
}
}
[/code]

  • Note that we are using @NoSql annotation
  • Instead of @Column for binding a field with a column in a relational database, the @Field has been used
  • @Embedded is a persist strategy that used for embed document within the body of other document

PrimeFaces Pie Chart Component

Representation of data is one of the most challenges with JSF implementation vendor. Charts is one of the primary components that have been coming with the PrimeFaces distribution, one of them is the Pie chart. Pie chart displays category-data in a pie graphic.

Here is the PieChart tag information and attributes defined with the PieChart.

PieChart General Info

Pie Attributes

The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – DataTable – User Registration </h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Full Name:"/>
<p:inputText value="#{registerationBean.user.fullName}"/>
<h:outputText value="Enter Age:"/>
<p:inputText value="#{registerationBean.user.age}"/>
<h:outputText value="Enter Status [Example A, B, C or D]:"/>
<p:inputText value="#{registerationBean.user.status}"/>
<h:outputText value="Enter Address"/>
<p:inputText value="#{registerationBean.user.address.addressValue}"/>
</h:panelGrid>
<h:panelGrid columns="1">
<p:pieChart value="#{registerationBean.model}" legendPosition="w"></p:pieChart>
</h:panelGrid>
<h:commandButton value="Save User" action="#{registerationBean.saveUser}"/>
<br/>

</h:form>
</f:view>
</html>
[/code]

Managed Bean

RegistrationBean.java

[code lang=”java”]
package net.javabeat.primefaces.presenation;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import net.javabeat.eclipselink.persistence.data.User;

import org.primefaces.component.chart.pie.PieChart;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean
@SessionScoped
public class RegisterationBean {
static EntityManagerFactory factory = null;
static EntityManager em = null;

static {
factory = Persistence.createEntityManagerFactory("mongoPU");
em = factory.createEntityManager();
}

private User user = new User();
private PieChartModel model = new PieChartModel();

int aCounter = 0;
int bCounter = 0;
int cCounter = 0;
int dCounter = 0;

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

@SuppressWarnings("unchecked")
public PieChartModel getModel() {

// At each rendering of data, a query has made upon mongo data.
Query query = em.createQuery("SELECT u FROM User u");
// Fetch the all users
List<User> users = query.getResultList();
// Categorize Users
for(User u : users){
if(u.getStatus().equals("A")){
aCounter++;
}
if(u.getStatus().equals("B")){
bCounter++;
}
if(u.getStatus().equals("C")){
cCounter++;
}
if(u.getStatus().equals("D")){
dCounter++;
}
}
this.model = new PieChartModel();
// Fill the model
model.set("A", aCounter);
model.set("B", bCounter);
model.set("C", cCounter);
model.set("D", dCounter);
return model;
}

public void setModel(PieChartModel model) {
this.model = model;
}

public String saveUser(){
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
this.user = new User();
return "";
}
}
[/code]

Persistence Context

persistence.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="mongoPU" transaction-type="RESOURCE_LOCAL">
<class>net.javabeat.eclipselink.persistence.data.User</class>
<class>net.javabeat.eclipselink.persistence.data.Address</class>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
<property name="eclipselink.nosql.property.mongo.port" value="27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
<property name="eclipselink.nosql.property.mongo.db" value="JavaBeat"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
[/code]

Primefaces + EclipseLink JPA / NOSQL + MongoDB Integration

The below snapshots show you the using of MongoDB for storing the users and retrieving them again for drawing the Pie Chart. Pie Chart is categorized based on the status that has the value among of set A, B, C and D.

At the same time, a find query db.USER.find() has been executed to ensure that the Pie Chart has executed a correct query into USER collections.

Pie Chart Used In Registration Form

  • Save user has invoked the saveUser method, that’s in turn the saving is being proceed.
  • GetModel will reset the Pie model for next coming filling.

Mongo Records

  • When the database is connected via mongo.exe, the user has the ability to inquiry the database.
  • The db implicit object represnts the connected database, which has the value of JavaBeat.
  • By using the command db.USER.find(), the user has the ability to see all of the registered users.

[wpdm_file id=77]

Filed Under: JSF Tagged With: EclipseLink, JPA, JSF 2.0, MongoDB, NOSQL, PrimeFaces

PrimeFaces Collector Example

April 18, 2014 by Amr Mohammed Leave a Comment

Collector is a simple utility to manage collections declaratively, collector requires a collection and a value to work with. It’s important to override equals and hashCode methods of the value object to make collector work.

Even you would be adding a certain object into list of the same type of that object, however, you have the ability of adding a certain object into list from the same kind by using the Collector component, so no need for defining a method for doing the add operation.

1. The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Collector </h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Name:"/>
<p:inputText value="#{registrationBean.user.name}"/>
<h:outputText value="Enter Age:"/>
<p:inputText value="#{registrationBean.user.age}"/>
<h:outputText value="Enter Status [Example A, B, C or D]:"/>
<p:inputText value="#{registrationBean.user.status}"/>
</h:panelGrid>
<p:commandButton value="Add" ajax="false">
<p:collector value="#{registrationBean.user}" unique="false" addTo="#{registrationBean.users}"></p:collector>
</p:commandButton>
<br/>
<br/>
<br/>
<p:dataTable id="dataTable" value="#{registrationBean.users}" var="user" border="1">
<p:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{user.name}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Status"/>
</f:facet>
<h:outputText value="#{user.status}"/>
</p:column>
</p:dataTable>
</h:form>
</f:view>
</html>
[/code]

2. User Data Type

User.java

[code lang=”java”]
package net.javabeat.primefaces.data;

public class User {
private String name;
private String age;
private String status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
[/code]

3. The Managed Bean

RegistrationBean.java

[code lang=”java”]
package net.javabeat.primefaces;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import net.javabeat.primefaces.data.User;
@ManagedBean
@SessionScoped
public class RegistrationBean {
private List<User> users = new ArrayList<User>();
private User user = new User();
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
[/code]

4. Primefaces Collector Example Demo

The below snapshot show you the using of Collector for adding a certain object into defined list.

Primefaces - Collector Example

[wpdm_file id=76]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces ColorPicker Example

April 18, 2014 by Amr Mohammed Leave a Comment

ColorPicker is an input component with a color palete, where it’s value should be a hex string. ColorPicker has two modes, default mode is popup and other available option is inline. Inline mode displays the picker directly into the view.

1. ColorPicker Tag Info

ColorPicker General Info

2. ColorPicker Tag Attributes

ColorPicker Attribute

ColorPicker Attribute

3. The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – ColorPicker </h2>
<p:colorPicker value="#{colorPicker.color}" mode="inline"></p:colorPicker>
#{‘ ‘}
<h:commandButton value="Display" action="#{colorPicker.action}"></h:commandButton>
#{‘ ‘}
<h:outputText value="#{colorPicker.color}"></h:outputText>
</h:form>
</f:view>
</html>
[/code]

4. Managed Bean

ColorPicker.java

[code lang=”java”]
package net.javabeat.primefaces;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class ColorPicker {

private String color;

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public String action(){
return "";
}
}
[/code]

5. Primefaces ColorPicker Demo

The below snapshot shows you the using of colorPicker component.
&nbps;
ColorPicker Demo

[wpdm_file id=75]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces Clock Example

April 16, 2014 by Amr Mohammed Leave a Comment

Primefaces provides a time component for taking the time from the user by using the Clock component. Clock displays server or client date time live. When it comes for displaying the server time, the Clock component provides AutoSync feature in server mode that can sync the clock with the server periodically.

1. Clock Tag Info

Primefaces Clock General Info

2. Clock Tag Attributes

Primefaces Clock Attributes

3. The View

index.xhtml

[code lang=”xml”]<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Clock</h2>
<p:clock mode="server" pattern="HH:mm:ss dd-MM-yyyy"></p:clock>
</h:form>
</f:view>
</html>[/code]

4. PrimeFaces Clock Demo

The below snapshot shows you the clock component, and how it’s rendered.

Primefaces Clock Example

[wpdm_file id=74]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces Captcha Example

April 16, 2014 by Amr Mohammed Leave a Comment

Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart)  is a type of challenge response test used in computing to determine whether or not the user is a human. PrimeFaces had provided such a component when the first version released. The component tag is <p:captcha/>.

Captcha is implemented as an input component with a built-in validator that is integrated with reCaptcha. reCAPTCHA is a free service to protect your website from spam and abuse provided by Google.

  • Read : PrimeFaces Tutorials

1. Captcha Tag Info

Captcha Tag Info

2. Captcha Tag Attributes

Captcha Tag Attributes

Captcha Attributes 2

3. Getting Public & Private Key

For getting the public and private key for be able of using Primefaces Captcha component, you have to visit the following link (After login) and follow the below remaining steps:

  • Press Get reCAPTCHA.
  • Press Sign Up Now !.
  • Put your domain inside the input box that follow word Domain.
  • Press Create.
  • Copy Public Key & Private Key that have provided dynamically.

4. Configure the web.xml

By copying the public and private keys that listed above, you have to configure the web.xml file, in order for getting working Captcha. In case, you’ve omitted the mentioning of such those keys, you will be getting an exception like below:

[code lang=”java”]
Apr 16, 2014 4:09:58 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/JavaBeat-Primefaces-V4] threw exception [Cannot find public key for catpcha, use primefaces.PUBLIC_CAPTCHA_KEY context-param to define one] with root cause
javax.faces.FacesException: Cannot find public key for catpcha, use primefaces.PUBLIC_CAPTCHA_KEY context-param to define one
[/code]

The snippet of code that would be adding for the web.xml is as follow:

[code lang=”xml”]
<context-param>
<param-name>primefaces.PUBLIC_CAPTCHA_KEY</param-name>
<param-value>YOUR_PUBLIC_KEY</param-value>
</context-param>

<context-param>
<param-name>primefaces.PRIVATE_CAPTCHA_KEY</param-name>
<param-value>YOUR_PRIVATE_KEY</param-value>
</context-param>
[/code]

5. Managed Bean

[code lang=”java”]
package net.javabeat.primefaces;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

@ManagedBean
@SessionScoped
public class Captcha {
public void check(ActionEvent e){
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Your Code Is Correct !",null));
}
}
[/code]

6.The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Captcha</h2>
<p:messages id="msg"/>
<p:captcha id="captcha"></p:captcha>
<br/>
<p:commandButton value="Check" actionListener="#{captcha.check}"
ajax="false"></p:commandButton>
</h:form>
</f:view>
</html>
[/code]

7. Primefaces Captcha Example Demo

The below snapshots shows you the using of captcha and how could the success code

Primefaces Captcha Example Demo

Primefaces Captcha Example 2

Primefaces Captcha Example 3

[wpdm_file id=73]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces Button Example

April 16, 2014 by Amr Mohammed Leave a Comment

One of the component that already extended by the Primefaces is the p:button, which extends the basic functionality of h:button. p:button usage is same as standard h:button, an outcome is necessary to navigate using GET requests, but Primefaces has added some minimal extra features such as skinning. Also, p:button has supported the icon rendering via style or via a newly added attribute icon. Take in your consideration the capability of using the Primefaces icons that already provided at the following link.

  • Read : PrimeFaces Tutorials

1. PrimeFaces Button Tag Info

Button Tag Info

2. PrimeFaces Button Tag Attributes

Button Tag Attributes

3. The Views

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Button</h2>
<br/>
<h:outputText value="Navigate Into Home Via GET Primefaces Button"/>
#{‘ ‘}
<p:button outcome="home" value="Navigate Home" title="Navigate Button Without Icon"></p:button>
</h:form>
</f:view>
</html>
[/code]

home.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – Button</h2>
<br/>
<h:outputText value="Go To Favourite Page"/>
#{‘ ‘}
<p:button outcome="index" icon="ui-icon ui-icon-heart" title="Go Index"></p:button>
</h:form>
</f:view>
</html>
[/code]

4. PrimeFaces Button Demo

The below snapshots show you the using of p:button, in addition to explain the using of icon property.

PrimeFaces Button Demo

Primefaces Button Example 2

[wpdm_file id=72]

Filed Under: JSF Tagged With: PrimeFaces

PrimeFaces AutoComplete + Client Side API

April 16, 2014 by Amr Mohammed Leave a Comment

One of the robust things that could consider when you come for adapting the Primefaces implementation is the Client Side API, this API provides you a full functional facility to control the component that you want to use. AutoComplete isn’t an exception of this role, it’s also supported by a rich amount of services that could be invoked through the Java Script.

Before accessing the AutoComplete component, you have to define what’s already defined before and named as WidgetVar. WidgetVar is a Primefaces concept, at which the JavaScript code works.

  • Read : PrimeFaces Tutorials

You’ve already seen the invoking of AutoComplete behaviors by the user interaction with the component itself, so behavior like close can be happened once the user has unfocused the component while the suggestions are shown. And behavior like search can be happened once the user has typed a text inside the component. All of these behaviors can be achieved through an API provided for the component itself in addition for other behaviors such as activate the search and deactivate it.

This tutorial explains how to implement AutoComplete with the help of Client Side API in PrimeFaces.

1. Client Side API for AutoComplete

Primefaces provides you the following api that could be invoked via of JavaScript.

  • close: Hides suggested items menu
  • disable: Disables the input field
  • enable: Enables the input field
  • search: Initiates a search with given value
  • activate: Activates search behavior
  • deactivate: De Activates search behavior

2. The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
<script>
function close(){
PF(‘autoVar’).close();
}

function disable(){
autoVar.disable();
}

function enable(){
PF(‘autoVar’).enable();
}

function deactivate(){
autoVar.deactivate();
}

function activate(){
PF(‘autoVar’).activate();
}

function search(){
PF(‘autoVar’).search(‘Ol’);
}
</script>
</h:head>
<f:view afterPhase="#{autoComplete.phaseListener}">
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – AutoComplete + Client Side API</h2>
<h:outputText value="Enter name of the player you wish to see statistics for :"/>
#{‘ ‘}
<p:autoComplete widgetVar="autoVar" id="auto" value="#{autoComplete.players}"
completeMethod="#{autoComplete.complete}"
var="player"
itemValue="#{player}"
itemLabel="#{player.playerName}"
converter="#{playerConverter}"
multiple="true">
<f:facet name="itemtip">
<h:panelGrid>
<f:facet name="header">
<h:graphicImage value="/resources/images/#{player.playerImage}"></h:graphicImage>
</f:facet>
<h:outputText value="Name: "/>
<h:outputText value="#{player.playerName}"/>
<h:outputText value="Position: "/>
<h:outputText value="#{player.playerPosition}"/>
</h:panelGrid>
</f:facet>
<p:ajax event="itemSelect" listener="#{autoComplete.handleSelect}" update="msg"></p:ajax>
<p:ajax event="itemUnselect" listener="#{autoComplete.handleUnSelect}" update="msg"></p:ajax>
</p:autoComplete>
<br/>
<p:messages id="msg"/>
<br/><br/>
<br/><br/>
<h:panelGrid columns="2" cellpadding="5px;" border="1">
<f:facet name="header">
<h2>Java Script Actions</h2>
</f:facet>
<h:commandLink value="Search About Players Starting With Ol" onclick="search();return false;" title="This action will search about players their names starting with Ol"/>
<h:commandLink value="Close Suggestions" onclick="close();return false;" title="This action will close the suggestions"/>
<h:commandLink value="Activate Search Behavior" onclick="activate();return false;" title="This action will activate the search by using client side api"/>
<h:commandLink value="Deactivate Search Behavior" onclick="deactivate();return false;" title="This action will de activate the search by using client side api"/>
<h:commandLink value="Disable AutoComplete" onclick="disable();return false;" title="This action will disable the input"/>
<h:commandLink value="Enable AutoComplete" onclick="enable();return false;" title="This action will enable the input"/>
</h:panelGrid>
</h:form>
</f:view>
</html>
[/code]

3. Managed Bean

AutoComplete.java

[code lang=”java”]
package net.javabeat.primefaces;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;

import net.javabeat.primefaces.data.Player;
import net.javabeat.primefaces.util.PlayerDataSource;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;

@ManagedBean
@SessionScoped
public class AutoComplete {
@ManagedProperty("#{playerDataSource}")
private PlayerDataSource ds;

private List<Player> players;

public AutoComplete (){

}

public List<Player> complete(String query){
// Assumed Datasource
return ds.queryByName(query);
}

public List<Player> getPlayers() {
return players;
}

public void setPlayers(List<Player> players) {
this.players = players;
}

public PlayerDataSource getDs() {
return ds;
}

public void setDs(PlayerDataSource ds) {
this.ds = ds;
}

public void handleSelect(SelectEvent e){
Player p = (Player)e.getObject();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO,
"Add Player :: Player Info: ID :: "+ p.getPlayerId() + " :: Name :: "+p.getPlayerName(),""));
}

public void handleUnSelect(UnselectEvent e){
Player p = (Player)e.getObject();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Remove Player :: Player Info: ID :: "+ p.getPlayerId() + " :: Name :: "+p.getPlayerName(),""));
}

public void phaseListener(PhaseEvent e){
List<FacesMessage> messages = e.getFacesContext().getMessageList();
System.out.println(messages.size());
}
}
[/code]

4. The Datasource

PlayerDataSource.java

[code lang=”java”]
package net.javabeat.primefaces.util;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import net.javabeat.primefaces.data.Player;
@ManagedBean
@SessionScoped
public class PlayerDataSource {
public List<Player> players = new ArrayList<Player>();

public PlayerDataSource(){
// Assumed Player
Player player = new Player();
player.setPlayerId("1");
player.setPlayerName("Anderias Muller");
player.setPlayerPosition("CF");
player.setPlayerAge("24");
player.setPlayerImage("am.png");

// Add Player
players.add(player);

// Assumed Player
player = new Player();
player.setPlayerId("2");
player.setPlayerName("Olaf Thon");
player.setPlayerPosition("CM");
player.setPlayerAge("29");
player.setPlayerImage("ot.png");

// Add Player
players.add(player);

// Assumed Player
player = new Player();
player.setPlayerId("3");
player.setPlayerName("Oliver Khan");
player.setPlayerPosition("GK");
player.setPlayerAge("31");
player.setPlayerImage("ok.png");

// Add Player
players.add(player);

}

public List<Player> getPlayers() {
return players;
}

public void setPlayers(List<Player> players) {
this.players = players;
}

public List<Player> queryByName(String name){
// Assumed search using the startsWith
List<Player> queried = new ArrayList<Player>();
for(Player player: this.players){
if(player.getPlayerName().startsWith(name)){
queried.add(player);
}
}
return queried;
}
}
[/code]

5. The Converter

PlayerConverter.java

[code lang=”java”]
package net.javabeat.primefaces.converter;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import net.javabeat.primefaces.data.Player;
import net.javabeat.primefaces.util.PlayerDataSource;
//To be considered by the JavaServer Faces As Managed Bean
// & Make the converter Eligible for use @ManagedProperty
@ManagedBean
@RequestScoped
@FacesConverter
public class PlayerConverter implements Converter{
@ManagedProperty(value="#{playerDataSource}")
private PlayerDataSource ds;

public PlayerDataSource getDs() {
return ds;
}

public void setDs(PlayerDataSource ds) {
this.ds = ds;
}

@Override
public Object getAsObject(FacesContext context, UIComponent component,String value) {
for(Player p : ds.getPlayers()){
if(p.getPlayerId().equals(value)){
return p;
}
}
return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component,Object value) {
if(value instanceof Player){
Player player = (Player)value;
return player.getPlayerId();
}
return "";
}
}
[/code]

6. Player Pojo

Player.java

[code lang=”java”]
package net.javabeat.primefaces.data;

public class Player {
private String playerId;
private String playerName;
private String playerPosition;
private String playerAge;
private String playerImage;

public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerPosition() {
return playerPosition;
}
public void setPlayerPosition(String playerPosition) {
this.playerPosition = playerPosition;
}
public String getPlayerAge() {
return playerAge;
}
public void setPlayerAge(String playerAge) {
this.playerAge = playerAge;
}

public String getPlayerImage() {
return playerImage;
}
public void setPlayerImage(String playerImage) {
this.playerImage = playerImage;
}
public boolean equals(Object obj){
if(obj instanceof Player){
Player player = (Player)obj;
if(this.playerId.equals(player.getPlayerId())){
return true;
}
}
return false;
}

public int hashCode(){
return this.playerId.hashCode();
}
}
[/code]

7. PrimeFaces AutoComplete + POJO + Client Side API Demo

AutoComplete Pojo + ClientSide

Note the following points when you comes to run the demo:

  • The search link should do search on all players that have names starting with Ol, cause the search function provide this value as a parameter.
  • Close suggestions, should hide the suggestions only, with capability of showing it again.
  • Deactivate search will prevent you from doing a search through using client side API.
  • Activate search will allow you to do a search via client side API.
  • Disable, should disable the input. so the user couldn’t be capable to enter any text within it.
  • Enable, will enable the input again for accepting the user inputs.

[wpdm_file id=66]

Filed Under: JSF Tagged With: PrimeFaces

Primefaces BreadCrumb Example

April 16, 2014 by Amr Mohammed Leave a Comment

Primefaces provides different kinds of navigation components, one of among them is BreadCrumb, it’s one of the navigation component that provides contextual information about page hierarchy in the workflow. In that a steps are defined as child menuitem components in breadcrumb. By the way the creating of menuitems can be done from through one of the following way:

  • Declarative: Where the menuitems are defined within the breadcrumb component.
  • Programmatic: Where the breadcrumb component defines a MenuModel using the model attribute.

The declarative way get involved using a <p:menuItem/> Tag, whereas the programmatic way get involved using a DefaultMenuModel & DefaultMenuItem. This tutorial explains the way how to use the BreadCrumb with PrimeFaces framework. If you have any questions, please write it in the comments section.

  • Read : PrimeFaces Tutorials

1. PrimeFaces BreadCrumb Tag Info

PrimeFaces BreadCrumb Tag Info

2. PrimeFaces BreadCrumb Tag Attributes

PrimeFaces BreadCrumb Tag Attributes

3. Managed Bean

BreadCrumb.java

[code lang=”java”]package net.javabeat.primefaces;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.MenuModel;

@ManagedBean
@SessionScoped
public class BreadCrumb {
private MenuModel menuModel = new DefaultMenuModel();

public BreadCrumb(){

// Initialize
this.menuModel = new DefaultMenuModel();

// Create index menuItem
DefaultMenuItem index = new DefaultMenuItem();
index.setValue("Index");
index.setCommand("#{breadCrumb.navigateIndex}");

// Add menuItems
this.menuModel.addElement(index);
}

public MenuModel getMenuModel() {
return menuModel;
}

public void setMenuModel(MenuModel menuModel) {
this.menuModel = menuModel;
}

public String navigateIndex(){
// Initialize
this.menuModel = new DefaultMenuModel();

// Create index menuItem
DefaultMenuItem index = new DefaultMenuItem();
index.setValue("Index");
index.setCommand("#{breadCrumb.navigateIndex}");
index.setUrl("index.xhtml");

// Add menuItems
this.menuModel.addElement(index);

return "index";
}

public String navigateHome(){
// Initialize
this.menuModel = new DefaultMenuModel();

// Create index menuItem
DefaultMenuItem index = new DefaultMenuItem();
index.setValue("Index");
index.setCommand("#{breadCrumb.navigateIndex}");
index.setUrl("index.xhtml");

// Create home menuItem
DefaultMenuItem home = new DefaultMenuItem();
home.setValue("Home");
home.setCommand("#{breadCrumb.navigateHome}");
index.setUrl("home.xhtml");

// Add menuItems
this.menuModel.addElement(index);
this.menuModel.addElement(home);

return "home";
}

public String navigatePrimefaces(){
// Initialize
this.menuModel = new DefaultMenuModel();

// Create index menuItem
DefaultMenuItem index = new DefaultMenuItem();
index.setValue("Index");
index.setCommand("#{breadCrumb.navigateIndex}");
index.setUrl("index.xhtml");

// Create home menuItem
DefaultMenuItem home = new DefaultMenuItem();
home.setValue("Home");
home.setCommand("#{breadCrumb.navigateHome}");
index.setUrl("home.xhtml");

// Add menuItems
this.menuModel.addElement(index);
this.menuModel.addElement(home);

// Create Primefaces menuItem
DefaultMenuItem primefaces = new DefaultMenuItem();
primefaces.setValue("Primefaces Tutorial");
primefaces.setCommand("#{breadCrumb.navigatePrimefaces}");

// Add menuItem
this.menuModel.addElement(primefaces);

return "primefaces";
}
}[/code]

4. The Views

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – BreadCrumb</h2>
<p:breadCrumb model="#{breadCrumb.menuModel}"></p:breadCrumb>
<br/>
<h:commandButton value="Go Home" action="#{breadCrumb.navigateHome}"></h:commandButton>
</h:form>
</f:view>
</html>
[/code]

home.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – BreadCrumb</h2>
<p:breadCrumb model="#{breadCrumb.menuModel}">
</p:breadCrumb>
<br/>
<h:commandButton value="Go Index" action="#{breadCrumb.navigateIndex}"></h:commandButton>
<h:commandButton value="Go Primefaces Tutorial" action="#{breadCrumb.navigatePrimefaces}"></h:commandButton>
</h:form>
</f:view>
</html>
[/code]

primefaces.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – BreadCrumb</h2>
<p:breadCrumb model="#{breadCrumb.menuModel}">
</p:breadCrumb>
<br/>
<h:commandButton value="Go Index" action="#{breadCrumb.navigateIndex}"></h:commandButton>
<h:commandButton value="Go Home" action="#{breadCrumb.navigateHome}"></h:commandButton>
</h:form>
</f:view>
</html>[/code]

5. Primefaces BreadCrumb + Programmatic Demo

Primefaces - BreadCrumb Example 1

Primefaces - BreadCrumb Example 2

Primefaces - BreadCrumb Example 3

6. Primefaces BreadCrumb + Declarative Demo

If you’ve decided using the BreadCrumb in a declarative manner, so the menuItem Tag will get involved for achieving that. Below you will find a sample of it.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h1>JavaBeat Primefaces Example</h1>
<h2>Primefaces – BreadCrumb</h2>
<p:breadCrumb>
<p:menuitem value="Home" url="#"></p:menuitem>
</p:breadCrumb>
<br/>
</h:form>
</f:view>
</html>
[/code]

[wpdm_file id=71]

Filed Under: JSF Tagged With: PrimeFaces

  • 1
  • 2
  • 3
  • …
  • 17
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved