Wednesday, February 2, 2011

PrimeFaces QuickStart Tutorial-Part1

PrimeFaces is an open source component library for JSF 2.0 with morethan 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

<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" >
    
    
        index.jsp
    
        
    
        Faces Servlet
        javax.faces.webapp.FacesServlet
        1
    

    
        Faces Servlet
        *.jsf
    
    
</web-app>

Create faces-config.xml in WEB-INF folder.

    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">
    
    

Welcome page index.jsp just forwards to login screen.


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">

    

    
                                                                                                                                   
   
</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 automcomplete for PrimeFaces tag in Eclipse. To enable AutoComplete,
Go to Window-->Preferences-->General-->ContentTypes
Select JSP and add .xhtml as file association.


You can download the sample as an Eclipse project Here

36 comments:

  1. Hi Dude, thanks for sharing information . I like the presentation though , could you tell me how did you highlighted the code , i am struggling to do same in my blog ?

    Thanks
    Javin
    How classpath works in Java

    ReplyDelete
  2. hai siva, can u post web.xml

    ReplyDelete
  3. Hi,
    web.xml is already there at the beginning.

    ReplyDelete
  4. Hi Siva. Sorry for my bad English. Can you help me. I'am use PrimeFaces 2.2, NetBeans 6.9.1, Glassfish 3.

    I have a problem with selection in .
    Why i change jsf page. Selection doesn't work.
    And when Table build from Bean file, and i change parametr (SQL query on page in textArea), my table rebuild, but select doesn't work.

    What happens a don't know....

    Can you help me...please.

    ReplyDelete
  5. Hi,
    Can u please send me your code snippets so that I can try to figure it out the problem.

    ReplyDelete
  6. I am unable to download the code...could you please upload it somewhere else?

    ReplyDelete
  7. Hi,
    I got the code, I will look into it and let you know soon.

    ReplyDelete
  8. Thanks for the Tutorial,
    it looks helpfully, even it it's not exactly what I am looking for. - A tutorial that shows how I put in PrimeFaces in SpringRoo.

    ReplyDelete
  9. 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? my email is csshankaravadivel@gmail.com

    Thanks again
    Sankar

    ReplyDelete
  10. Hey. Thanks for posting this!
    I am very impressed with PrimeFaces and want to get started on it.
    Your code here looks like a nice place to start. Any chance of including a downloadable war file, so I can use it has a foundation to build upon?
    Thanks.

    ReplyDelete
  11. Hi, The download link is added at the bottom of the article.

    https://sites.google.com/site/sivalabworks/sampleappdownloads/PrimeFaces.zip?attredirects=0&d=1

    ReplyDelete
  12. You have helped me understand onRowSelectUpdate and for this I am very grateful. I have the documentation, but it was not very clear!
    Cheers Sean

    ReplyDelete
  13. Great tutorial man, thank you.
    but instead of going with the *.jsf configuration you should now switch on to .xhtml part of the jsf. that the recommended one now i believe.
    good work.

    ReplyDelete
  14. Hi Shiva,

    Its Sunil, I am new to JSF, i tried with the above example but i am getting 404 error, it says login.jsp not found, i have not made any changes, i have taken the code as is. from index.jsp it is looking for login.jsp i couldn't get this. could you help me plz...

    ReplyDelete
  15. Hi shiva,

    i read your review about jsf on jan-2011 , is it true now ?

    ReplyDelete
  16. Hi Sasikumarm,
    I recently gave a one more try to JSF2/EJB3 stack.
    JSF2 improved over version 1.x but I feel still its hard to use because of its complex lifecycle.

    I personally feel like if we want rich UI we can go for Vaadin or any Ajax Toolkit like YUI/jQueryUI.

    Thanks,
    Siva

    ReplyDelete
  17. I am getting:
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.el.ELException: /home.xhtml: Property 'onUserSelect' not found on type com.primefaces.sample.UserManagedBean
    at com.sun.faces.facelets.compiler.AttributeInstruction.write(AttributeInstruction.java:94)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)

    Maybe someone know what's wrong?

    ReplyDelete
  18. It happens because there is no rowSelectListener in 3.0.M2; after deleting lines:

    rowSelectListener="#{userManagedBean.onUserSelect}"
    rowUnselectListener="#{userManagedBean.onUserUnselect}"

    I don't get error anymore.

    ReplyDelete
  19. Hi
    This link doesn't work anymore. Can you renew it please?
    Thanks

    https://sites.google.com/site/sivalabworks/sampleappdownloads/PrimeFaces.zip?attredirects=0&d=1

    ReplyDelete
  20. Hi,
    I hosted the code on github.
    Please check
    https://github.com/sivaprasadreddy/sivalabs-apps/tree/master/primefaces

    Thanks,
    Siva

    ReplyDelete
  21. Hi, ThanksI get the login screen then us: test pw:test and press login button I get this screen what is wrong?
    http://imageshack.us/photo/my-images/528/38809154.png/

    ReplyDelete
  22. hi Siva..

    A really nice post..

    What should I have to write in "onUserSelect" event of UserManagedBean

    Thanks

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Hi, I am new to JSF world and i have been thinking about integrating Spring MVC and using Primefaces view. do you know how to go about doing it.

    Regards
    Rishi

    ReplyDelete
  25. Im getting a blank screen when I run the code...No changes have been made..Can anyone help me???

    ReplyDelete
  26. can you plese provide me a line chart example with the above code

    ReplyDelete
  27. Failed to start service jboss.deployment.unit."PrimeFaces.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."PrimeFaces.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "PrimeFaces.war" getting this error;; can you please tel me y this

    ReplyDelete
  28. Hi Siva,

    Calendar is not getting popup. i'm using primefaces3.3 and myfaces 2.0 do i need to change/ update with any jars so that popup appears.

    Thanks in Advance.

    Regards,
    Ravi

    ReplyDelete
  29. Thanks for the tutorial author.

    ReplyDelete
  30. what's user and password for a testing , thanks

    ReplyDelete
  31. WARNING: /login.xhtml @14,83 value="#{userManagedBean.username}": Target Unreachable, identifier 'userManagedBean' resolved to null
    javax.el.PropertyNotFoundException: /login.xhtml @14,83 value="#{userManagedBean.username}": Target Unreachable, identifier 'userManagedBean' resolved to null
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:97)
    at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:91)
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1023)
    at javax.faces.component.UIInput.validate(UIInput.java:953)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1204)
    at javax.faces.component.UIInput.processValidators(UIInput.java:693)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
    at javax.faces.component.UIForm.processValidators(UIForm.java:240)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1159)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:72)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:722)

    ReplyDelete
    Replies
    1. Do you have a JSF ManagedBean named UserManagedBean?

      Delete
  32. Hi shiva,

    is it really good for large ERP system ???,does the performance parameter is good, i used it,its easy to use but what about its performance,is it responsive in such a way that can be visible in all browsers and some Android browsers. please reply

    ReplyDelete
  33. hi guys, im having some problems with the code, here is the error

    "The attribute dynamic is not defined in the component dataTable"

    the same with onRowSelectUpdate;onRowUnselectedUpdate;rowSelectListener;rowUnSelectListener

    and also

    "The attribute parser is not defined in the component column"

    any ideas?

    this is my html tag

    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://xmlns.jcp.org/jsf/core"

    and im running on JSF 2.2 with PrimeFace 5

    ReplyDelete
  34. I am getting following error after running your build example.
    HTTP Status 500 - java.lang.NullPointerException
    com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java:)

    Can you please help me on this issue.

    ReplyDelete