I am Siva, a passionate java developer, open source enthusiast, blogger. I like to cover Java, Struts, Spring, Hibernate, Ajax Tutorials, How-To's and Best Practices. Sivaprasadreddy is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

PrimeFaces QuickStart Tutorial-Part1

02.02.2011
| 157961 views |
  • submit to reddit

PrimeFaces is an open source component library for JSF 2.0 with more than 100 rich components. PrimeFaces is far better than many other JSF component libraries because of the following reasons:


1. Rich set of UI components (DataTable, AutoComplete, HtmlEditor, Charts etc).
2.No extra xml configuration is required and there is no required dependencies.
3. Built-in Ajax based on standard JSF 2.0 Ajax APIs.
4. Skinning Framework with 25+ built-in themes.
5. Awesome documentation with code examples.
    
Let us build a sample application using PrimeFaces with the following features:
1. A Login screen which accepts username and password and authenticate the user.
2. Upon successful login user will be shown a User Search screen. Users can search for users by their name. The search results will be displayed in a DataTable with pagination, sorting and filtering support.
3. Upon clicking on a row the user details will be displayed in a form.

First download JSF 2 jars from http://javaserverfaces.java.net/download.html
Place the jsf-api-2.0.3.jar, jsf-impl-2.0.3.jar and jstl-1.0.2.jar jars in WEB-INF/lib folder.
Download PrimeFaces from http://www.primefaces.org/downloads.html.
Place primefaces-2.2.RC2.jar in WEB-INF/lib folder.

Configure FacesServlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<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>*.jsf</url-pattern>
</servlet-mapping>

</web-app>

Create faces-config.xml in WEB-INF folder.
<?xml version="1.0" encoding="utf-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<!--
No ManagedBean declarations here as we are using @ManagedBean Annotations.
-->

</faces-config>
Welcome page index.jsp just forwards to login screen.
<jsp:forward page="login.jsf"></jsp:forward>
Create login.xhtml page.
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css" />
</h:head>
<h:body>
<center>
<p:panel header="Login Form" style="width: 350;">
<h:form>
<h:panelGrid columns="2" cellpadding="2">
<h:outputLabel for="#{userManagedBean.username}" value="UserName"/>
<h:inputText value="#{userManagedBean.username}" label="UserName"></h:inputText>
<h:outputLabel for="#{userManagedBean.password}" value="Password"/>
<h:inputSecret value="#{userManagedBean.password}"></h:inputSecret>
<h:commandButton type="submit" value="Login" action="#{userManagedBean.login}"></h:commandButton>
</h:panelGrid>
</h:form>
</p:panel>
<div><h:messages ></h:messages></div>
</center>
</h:body>
</html>

You can get the blusky theme from PrimeFaces bundle.

Create home.xhtml which contains UserSearchForm, Results dataTable and UserDetails Panel.

<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css" />
</h:head>
<h:body>
<center>
<h:form>
<p:panel header="Users Search Form" style="width: 700;">
<h:form>
<h:panelGrid columns="3" cellpadding="2">
<h:outputLabel for="#{userManagedBean.searchUser}" value="UserName"/>
<h:inputText value="#{userManagedBean.searchUser}" label="UserName"></h:inputText>
<h:commandButton type="submit" value="Search" action="#{userManagedBean.searchUser}"></h:commandButton>
</h:panelGrid>
</h:form>
</p:panel>


<p:dataTable var="user" value="#{userManagedBean.searchUsersResults}"
selection="#{userManagedBean.selectedUser}" selectionMode="single"
dynamic="true"
onRowSelectUpdate="userUpdateForm"
onRowUnselectUpdate="userUpdateForm"
rowSelectListener="#{userManagedBean.onUserSelect}"
rowUnselectListener="#{userManagedBean.onUserUnselect}"
paginator="true" rows="5" style="width: 700">
<p:column sortBy="#{user.userId}" filterBy="#{user.userId}">
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{user.userId}" />
</p:column>
<p:column sortBy="#{user.username}" filterBy="#{user.username}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.username}" />
</p:column>
<p:column sortBy="#{user.emailId}" filterBy="#{user.emailId}">
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{user.emailId}" />
</p:column>
<p:column parser="date" sortBy="#{user.dob}" filterBy="#{user.dob}">
<f:facet name="header">
<h:outputText value="DOB" />
</f:facet>
<h:outputText value="#{user.dob}" >
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:outputText>
</p:column>
</p:dataTable>
<p:panel id="userDetailsPanelId" header="Users Details" style="width: 700;">
<h:panelGrid columns="2" cellpadding="2" id="userUpdateForm" border="0" >
<h:outputLabel for="#{userManagedBean.selectedUser.userId}" value="UserId"/>
<h:inputText value="#{userManagedBean.selectedUser.userId}" style="width: 100;" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.username}" value="Username"/>
<h:inputText value="#{userManagedBean.selectedUser.username}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.emailId}" value="EmailId"/>
<h:inputText value="#{userManagedBean.selectedUser.emailId}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.gender}" value="Gender"/>
<h:inputText value="#{userManagedBean.selectedUser.gender}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.dob}" value="DOB"/>
<h:inputText value="#{userManagedBean.selectedUser.dob}" readonly="true">
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:inputText>

</h:panelGrid>
</p:panel>
</h:form>
</center>
</h:body>
</html>


Create User.java domain class.

package com.primefaces.sample;
import java.util.Date;

public class User
{
private Integer userId;
private String username;
private String emailId;
private String phone;
private Date dob;
private String gender;
private String address;

public User()
{}
public User(Integer userId, String username, String emailId, String phone,
Date dob, String gender, String address)
{
this.userId = userId;
this.username = username;
this.emailId = emailId;
this.phone = phone;
this.dob = dob;
this.gender = gender;
this.address = address;
}
//setter and getters
}

Create UserService.java which acts as a mock database table.

package com.primefaces.sample;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UserService
{
private static final Map<Integer, User> USERS_TABLE = new HashMap<Integer, User>();
static
{
USERS_TABLE.put(1, new User(1, "Administrator", "admin@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(2, new User(2, "Guest", "guest@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(3, new User(3, "John", "John@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(4, new User(4, "Paul", "Paul@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(5, new User(5, "raju", "raju@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(6, new User(6, "raghav", "raghav@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(7, new User(7, "caren", "caren@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(8, new User(8, "Mike", "Mike@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(9, new User(9, "Steve", "Steve@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(10, new User(10, "Polhman", "Polhman@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(11, new User(11, "Rogermoor", "Rogermoor@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(12, new User(12, "Robinhood", "Robinhood@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(13, new User(13, "Sean", "Sean@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(14, new User(14, "Gabriel", "Gabriel@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
USERS_TABLE.put(15, new User(15, "raman", "raman@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));

}
public Integer create(User user)
{
if(user == null)
{
throw new RuntimeException("Unable to create User. User object is null.");
}
Integer userId = this.getMaxUserId();
user.setUserId(userId);
USERS_TABLE.put(userId, user);
return userId;
}

public void delete(User user)
{
if(user == null)
{
throw new RuntimeException("Unable to delete User. User object is null.");
}
USERS_TABLE.remove(user.getUserId());
}

public Collection<User> getAllUsers()
{
return USERS_TABLE.values();
}

public User getUser(Integer userId)
{
return USERS_TABLE.get(userId);
}

public Collection<User> searchUsers(String username)
{
String searchCriteria = (username == null)? "":username.toLowerCase().trim();
Collection<User> users = USERS_TABLE.values();
Collection<User> searchResults = new ArrayList<User>();
for (User user : users)
{
if(user.getUsername() != null && user.getUsername().toLowerCase().trim().startsWith(searchCriteria))
{
searchResults.add(user);
}
}
return searchResults;
}

public void update(User user)
{
if(user == null || !USERS_TABLE.containsKey(user.getUserId()))
{
throw new RuntimeException("Unable to update User. User object is null or User Id ["+user.getUserId()+"] is invalid." );
}
USERS_TABLE.put(user.getUserId(), user);
}

protected Integer getMaxUserId()
{
Set<Integer> keys = USERS_TABLE.keySet();
Integer maxId = 1;
for (Integer key : keys)
{
if(key > maxId)
{
maxId = key;
}
}
return maxId;
}
}


Create UserManagedBean.java

package com.primefaces.sample;

import java.util.Collection;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

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

@ManagedBean
@ApplicationScoped
public class UserManagedBean
{
UserService userService = new UserService();

private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;

public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}

public User getSelectedUser()
{
if(selectedUser == null){
selectedUser = new User();
}
return selectedUser;
}

public void setSelectedUser(User selectedUser)
{
this.selectedUser = selectedUser;
}
public Collection<User> getSearchUsersResults()
{
return searchUsersResults;
}
public void setSearchUsersResults(Collection<User> searchUsersResults)
{
this.searchUsersResults = searchUsersResults;
}
public String getSearchUser()
{
return searchUser;
}
public void setSearchUser(String searchUser)
{
this.searchUser = searchUser;
}

public String login()
{
if("test".equalsIgnoreCase(getUsername()) && "test".equals(getPassword()))
{
return "home";
}
else
{
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage("Invalid UserName and Password"));
return "login";
}
}

public String searchUser()
{
String username = (this.searchUser == null)? "":this.searchUser.trim();
this.searchUsersResults = userService.searchUsers(username);
System.out.println(searchUsersResults);
return "home";
}

public String updateUser()
{
userService.update(this.selectedUser);
return "home";
}

public void onUserSelect(SelectEvent event)
{
}
public void onUserUnselect(UnselectEvent event)
{
}
}

That all we need to do. You can run the application and see the rich user interface with blusky theme.

By default we don't get auto-complete for PrimeFaces tag <p> in Eclipse. To enable AutoComplete,
Go to Window-->Preferences-->General-->ContentTypes
Select JSP and add .xhtml as file association.

From http://sivalabs.blogspot.com/2011/02/primefaces-quickstart-tutorial-part1.html

Published at DZone with permission of Sivaprasadreddy Katamreddy, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Jonathan Fisher replied on Wed, 2011/02/02 - 3:29pm

For anyone that's been burned by JSF 1.x, give JSF2.0 a try. They shouldn't have called it JSF, it's a completely new that's annotation driven. Primefaces is unique because it pushes JQueryUI to the browser via Ajax. It's a lot easier to develop with JSF2.0 than it is to debug javascript code! Great little tutorial! (other than the "c++ style" code formatting ;) )

Sivaprasadreddy... replied on Fri, 2011/02/04 - 12:55am in response to: Jonathan Fisher

@Jonathan Fisher,

I haven't deep dive into JSF2 but i haven't found any major improvements in JSF2 except annotation support over JSF1.x as of now. Could you please tell me or point me to some url where i can see what are the things improved/added in JSF2.x.

Thanks,
Siva.

Bogdan Marian replied on Fri, 2011/02/04 - 10:49am in response to: Sivaprasadreddy Katamreddy

This link could be of some use for your question: http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/

Armin Ruf replied on Mon, 2011/09/05 - 4:06am

Hi all, how can I get a complete primefaces tutorial?

Kannan Raghupathy replied on Fri, 2011/10/14 - 1:41am in response to: Sivaprasadreddy Katamreddy

Hi Siva,

 How r u doing?

 I am in the process of creating a new project using PrimeFaces.  Which is good IDE to design my JSF pages using PrimeFaces?  Eclipse or Netbeans.

 Please suggest me the best way to do it?

 Thanks in advance.

Kannan

Thomas Kern replied on Thu, 2012/09/06 - 10:51am

Thanks for the great tutorial. There are very few(almost nil) documents available online for Primefaces. You have taken a more serious example to explain Primefaces and it was really helpful.

I am exploring Primefaces. Would it be a good idea to invest on the ebook available on Primefaces site? Have you tried that? If you have other resources on this, can you share with me?

http://www.java-tips.org 

Santosh Kumar replied on Tue, 2012/04/24 - 12:00am in response to: Kannan Raghupathy

Hi Kannan , How are you ? As you said that your given the jsf and primefaces projects...right now i am also in the same condition can you please guide me over these how to proceed . I was struck in the middle of calendar - Schedule Link just can you please provide me the Link which will be useful. Thanks Santosh

Pankaj Oak replied on Mon, 2012/07/23 - 1:19am

Hi All.

 

I am working on Primefaces pdfexporter part to export PDF.

I am loking for functionlity where exported PDF will have page 1 of 5 in bottom.

Currently i have used Pdf Preprocessor where i am creating instance of HeaderFooter with numbering as true.But that is only diplyaing page 1 , page 2 and not page 1 of 2.

 

Please help me to resolve this.

Ravinderjeet Si... replied on Sun, 2013/05/12 - 3:22pm

Hi, the example publish here is not working completely..

The rowselection attribute of datatable of above example is not working...  if possible, someone could please post the working code....


Thanks in advance.

Ravinderjeet

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.