PrimeFaces Quick Start Tutorial - Part1
Join the DZone community and get the full member experience.
Join For FreePrimeFaces 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@ApplicationScopedpublic 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
Opinions expressed by DZone contributors are their own.
Comments