JSF 2.0 Tutorial

jsf2-tutorials

JavaServer Faces (JSF) 2.0, is an MVC web framework which focus on simplifies building user interfaces (comes with 100+ ready UI tags) for Java web application and make reusable UI component easy to implement. Unlike JSF 1.x, almost everything is declared in faces-config.xml, with JSF 2.0, you are allowed to use annotation to declare navigating, managed bean or CDI bean, which make your development easier and faster.

In this tutorial, it provides many step by step examples and explanations on using JavaServer Faces (JSF) 2.0 framework.

Happy learning JSF 2.0 šŸ™‚

Quick Start

Some quick start examples for JSF 2.0

  • JSF 2.0 hello world example
    A JavaServer Faces (JSF) 2.0 hello world example, shows the JSF 2.0 dependencies, basic annotations and configurations. Let you have a quick idea about how JSF 2.0 look like, and also how it differs from JSF 1.x.
  • JSF 2.0 + Ajax hello world example
    In JSF 2.0, coding Ajax has been just like coding a normal HTML tag, it’s extremely easy. In this tutorial, you will restructure the last JSF 2.0 hello world example, so that, when the button is clicked, it will make an Ajax request instead of submitting the whole form.
  • How to make Eclipse IDE supports JSF 2.0
    Here’s a quick guide to show how to enable the JSF 2.0 features in Eclipse projects.
  • Resources (library) in JSF 2.0
    In JSF 2.0, all your resources files like css, images or JavaScript, should put into a ā€œresourcesā€ folder in the root of your web application. In JSF 2.0 terminology, all the sub-folder name of the ā€œresourcesā€ folder is considered as a ā€œlibraryā€ in JSF 2.0 web application. Later, you can reference this ā€œlibraryā€ with JSF tag’s library attribute.

Managed Bean

About managed bean configuration and injection in JSF 2.0

  • Configure Managed Beans in JSF 2.0
    In JSF 2.0, Java bean that can be accessed from JSF page is called Managed Bean. The managed bean can be a normal Java bean, which contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).
  • Injecting Managed beans in JSF 2.0
    In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a managed bean into the property of another managed bean.

Navigation

How the navigation works in JSF 2.0

  • Implicit Navigation in JSF 2.0
    Now, JSF 2 come out a new ā€œauto view page resolverā€ mechanism named ā€œimplicit navigationā€œ, where you don’t need to declare the above navigation rule, instead, just put the ā€œview nameā€ in the action attribute and JSF will find the correct ā€œview pageā€ automatically.
  • Conditional Navigation Rule in JSF 2.0
    JSF 2 comes with a very flexible conditional navigation rule to solve the complex page navigation flow.
  • JSF “form-action” navigation rule example
    In JSF navigation rule, you may encounter a situation where two separate actions return a same “outcome” in a page. In this case, you can use “form-action” element to differentiate the two navigation cases.
  • JSF : Page Forward vs Page Redirect
    By default, JSF performs a server page forward while navigating to another page. See following example to differentiate between the page forward and page redirect.

Resource Bundles

JSF’s message manipulation and Internationalization.

  • JSF 2.0 and Resource Bundles example
    In this tutorial, we show you the use of resource bundle to display the messages in the JSF 2.0. For maintainability concern, it’s recommended to put all the messages in the properties file, instead of hard-code the message in the page directly.
  • JSF 2 Internationalization example
    JSF 2.0 Internationalization or multiple language example.

JSF Tag Library

Standard JSF 2 form’s tag component.

Table Manipulation

Add, update, delete and sorting data in via JSF’s dataTable.

Facelets Tags

Doing layout template with JSF 2.0 facelets tags.

Converters & Validation

Standard Convertors and validator tags in JSF 2.0

Composite Components

Reusable components in JSF 2.0

Event Handler

JSF 2 comes with many event handler to hijack the JSF’s life cycle.

Integrate with Other Frameworks

How to integrate JSF with external services.

FAQ

Some Frequent ask questions in JSF 2.0

Common Errors

Some common error messages in JSF 2.0

Reference

Some useful reference site for further study on JSF 2.0

  1. JSF official Website
  2. The JSF application lifecycle
  3. Converter and Validation
  4. Communication in JSF

118 comments on “JSF 2.0 Tutorial

  1. i have been developing web application since 5 days .i’m using spring+Hibernate+jsf when i run .xhtml file its showing “Uh-oh, something went wrong! Error Code: 404 ” this error in browser and

  2. Will you people PLEASE quit using annotation beans in JSF. It is the worst of all bad ideas. It is hardcoding config data inside java source. Nothing could be worse.

    If you have only a few years experience in programming, PLEASE do not write these blogs.

  3. This site is very useful and the UX is great. Hope you can add tutorials on JSF authentication and authorization

  4. Hello, I have a quick question about icefaces tag outputResource. I am trying to remove icefaces completely out of my projects and use myfaces instead, can you give me an equivalent implementation of ice:outputResource in myfaces, it could be a myface tag or equivalent implementation using html and js that i could use. Also checked tomahawk, trinidad component libraries for this.

  5. Hello, Just my personal preference but I have a strong negative thinking about annotations. To me this is what we call “hard-coding” which I believe should be avoided at all cost. Using xml configuration the server doesnt have to be restarted.

    All configuration should be table/xml driven. Other wise you have to re-generate the war file and re-install it for the smallest of changes. Not practical, and goes against the entire principal of JSF.

  6. Really helpful info.

    Small request:
    It will be useful if you could add a tutorial on how to extend JSF components

    I have a quick request:
    Do you know how to make primefaces panel component on a dashboard component resizable?

  7. Hi, I want to know how can I move the jsf (xhtml) file to a folder, for example: from /web (root folder) to /web/faces? Could you help me with that?

  8. Hello im looking for a example of BLOB upload to database using hibernate to save the pdf and jsf 2.0 (xhtml pages) to display the upload buttons .I only found examples of upload only with jsf or only with hibernate , not integrated.Can anyone help me with that? thank you.

  9. Hey , i created a jsf2.2 web application and deployed it to a free web hosting service . I found that the text boxes are not editable and the commandButton does not appear however it works very el on Glassh Fish 4.0 local server . What’s the problem ? Please answer asap .

  10. Can u please tell me the difference between Backing Bean and Manged Bean ?
    Is both are same ..?
    Can you explain with an example.
    Please replay ..

    1. Both are used interchangeably usually. But as such managed beans contain data for the screen, while backing beans hold references of components of the screen. You may not need to hold the references of components on the screen in a backing bean if you don’t plan to add components dynamically. If it all sounds too complicated then you can simply assume that both are same.

  11. Hi
    I am facing some problem while setting up an environment.
    I have to use jsf 2.x with facelets and richfaces on Glassfish V2.
    please help me to setup this
    Thanks
    Abdul

  12. Hi, Please consider me as your new fan. I am starting a new J2EE financial project which will also have lots of menus, graphs, charts. I was thinking using JSF2 with PrimeFaces, do you think that is a good approach or is any other MVC a preferred framework of choice (Spring MVC or something else). Many thanks in advance.

  13. hi
    I have included peimefaces jar in lib. and added it in deployment assembly.
    tags are coming in the pages with no errors.
    But when I am running it the primefaces is not working.
    what to do ?

  14. Wow, I just saw this tutorial after visiting BalusC’s zeef.com. I am an active user of PrimeFaces and participate in the forums, there, almost daily. I need to start recommending your tutorial! šŸ™‚

  15. it is a excellent resource for JSF as well as any technologies which is belong to Java

    Thanks Q very much

  16. Hi Mkyong,
    I am new in jsf 2 using primefaces libraries.But whats the correct jsf project Structure for devoloping A standard project.I mean Creating P pure MVC Project in JSF.Please Help Me

  17. Hi Mkyong,
    I am new to Richfaces and Jsp. I dont know how to configure Pom.xml file. So can u please give me a step by step tutorial for creating a project using richfaces4 using jsf2.0 in Eclipse using Maven.

  18. You have’t explained the 2 new scopes added in ver 2.0 – View scope. This is a major addition in ver 2.0. Also 2.2 has some @Flow scope added.

  19. welcomeJSF.jsp is

    
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
    <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    
    <%--
        This file is an entry point for JavaServer Faces application.
    --%>
    
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <title>JSP Page</title>
        </head>
        <body>
            <f:view>
                <h:form >
                    <h:dataTable id="tbl1" value="#{GetStaff.se}" border="1" var="tbl">
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="S.No"/>
                            </f:facet>
                            <h:outputText value="#{tbl.index}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Id"/>
                            </f:facet>
                            <h:outputText value="#{tbl.id}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Name"/>
                            </f:facet>
                            <h:outputText value="#{tbl.name}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="School"/>
                            </f:facet>
                            <h:outputText value="#{tbl.school}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Designation"/>
                            </f:facet>
                            <h:outputText value="#{tbl.desgn}" rendered="#{not tbl.enabled}"/>
                            <h:inputText value="#{tbl.desgn}" rendered="#{tbl.enabled}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value=""/>
                            </f:facet>
    
                            <<h:commandButton id="btn1" value="Edit" action="#{GetStaff.editAction(tbl,tbl.index)}" disabled="#{tbl.enabled}"/>
                            <h:commandButton id="btn2" value="Save" action="#{GetStaff.saveAction(tbl,tbl.index)}" disabled="#{not tbl.enabled}"/>
                            <h:commandButton id="btn3" value="Delete"/>
                        </h:column>
                    </h:dataTable>
                </h:form>
            </f:view>
        </body>
    </html>
    
    
  20. I am new to jsf. I cant seem to toggle between the edit and save buttons in the datatable for each row.

    The welcomeJSF.jsp is

    JSP Page

    <

    DbConnect.java is

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    /**
    *
    * @author user
    */
    public class DBConnect {

    Connection abc = null;
    Statement st = null;

    DBConnect() {
    try {
    Class.forName(“com.mysql.jdbc.Driver”);
    abc = DriverManager.getConnection(“jdbc:mysql://localhost/db_school”, “root”, “root”);
    st = abc.createStatement();
    System.out.println(“Connection Established…”);
    } catch (SQLException ex) {
    Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

    public void insert(String s) {
    try {
    int t = st.executeUpdate(s);
    System.out.println(“Value Inserted ” + t);
    } catch (SQLException ex) {
    Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

    public int selectId(String s) {
    int a = 0;
    try {
    ResultSet rs = st.executeQuery(s);
    a = rs.getInt(0);
    } catch (SQLException ex) {
    Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
    }
    return a;
    }

    int checkValidLogin(String sql1, String nm, String pw) {
    int FLAG = 0;

    try {
    ResultSet rs = st.executeQuery(sql1);
    while (rs.next()) {
    if (nm.equals(rs.getString(“u_uname”)) && pw.equals(rs.getString(“u_pwd”))) {
    FLAG = 1;
    // System.out.println(“success”);
    }
    }
    } catch (SQLException ex) {
    Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
    }
    return FLAG;
    }

    ResultSet selectAll(String a) throws SQLException {
    ResultSet rs = st.executeQuery(a);
    return rs;
    }
    }

    StaffEntity is

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    /**
    *
    * @author user
    */
    public class StaffEntity {

    private String name, desgn, school;
    private int id, index;
    private boolean enabled; //Default Value is False.

    public void setEnabled(boolean enabled) {
    this.enabled = enabled;
    }

    public boolean isEnabled() {
    System.out.println(“In Is “+this.enabled);
    return this.enabled;
    }

    // public void toggle(boolean enabled) {
    // System.out.println(“In Toggle “+enabled);
    // this.enabled = !enabled;
    // System.out.println(“After Toggle “+this.enabled);
    // }
    public int getIndex() {
    return index;
    }

    public void setIndex(int index) {
    this.index = index;
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    StaffEntity(int a, int b, String name, String school, String desgn) {
    this.index = a;
    this.id = b;
    this.name = name;
    this.school = school;
    this.desgn = desgn;
    // this.enabled=enabled;
    }

    public String getDesgn() {
    return desgn;
    }

    public void setDesgn(String desgn) {
    this.desgn = desgn;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getSchool() {
    return school;
    }

    public void setSchool(String school) {
    this.school = school;
    }

    public StaffEntity(){}
    }

    GetStaff.java is (Managed Bean)

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.faces.component.html.HtmlDataTable;
    import javax.faces.component.html.HtmlInputHidden;
    import javax.faces.context.FacesContext;

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    /**
    *
    * @author user
    */
    public class GetStaff {

    private StaffEntity[] se;
    private DBConnect db = new DBConnect();

    public StaffEntity[] getSe() throws SQLException {
    String s = “select * from tbl_staff”;
    ResultSet rs1 = db.selectAll(s);
    int i = 0;
    while (rs1.next()) {
    i++;
    // System.out.print(rs1.getInt(1));
    // System.out.print(rs1.getString(2));
    // System.out.print(rs1.getString(3));
    // System.out.print(rs1.getString(4));
    }

    se = new StaffEntity[i];
    rs1.beforeFirst();
    for (int j = 0; j < i; j++) {
    rs1.next();
    se[j] = new StaffEntity(j + 1, rs1.getInt(1), rs1.getString(2), rs1.getString(3), rs1.getString(4));
    }
    return se;
    }

    public void setSe(StaffEntity[] se) {
    this.se = se;
    }

    // public void toggle(boolean enabled) {
    // StaffEntity.enabled = !enabled;
    // System.out.println("In Toggle "+StaffEntity.enabled);
    // }

    public String editAction(StaffEntity s, int i) {
    s.setEnabled(true);
    System.out.println("Row Index is " + i);
    System.out.println("Name is " + s.getName());
    System.out.println("School is " + s.getSchool());
    System.out.println("Desgn is " + s.getDesgn());
    System.out.println("Enabled is " + s.isEnabled());
    return null;
    }

    public String saveAction(StaffEntity s, int i) {

    //get all existing value but set "editable" to false
    for (StaffEntity s1 : se){
    s1.setEnabled(false);
    }
    //return to current page
    return null;
    }
    }

    I get connect to db via dbconnect and can get values to datatable..but cant edit the row values.

    Expecting a reply.

  21. Hi

    We are currently working on prime faces 2.0.3 Snapshot jar.On our xhtml page if we write a p:menu it doesn’t work.I went to prime faces site,but it is recommended that to change the jar file itself.As project is running I cant change it.Please help us to use the component.

  22. Dear Sir

    I’m quite new in Java web app and your tutorials have been quite helpful to me. I appreciate them very much. I would be grateful if you can give a tutorial on how to use JasperReports with JSF and Glassfish.
    Thanks

  23. how to give colouring to the java code in web page..

    here below you have asked us to use

     Java source code here 

    , right .. but its not displaying the java code in coloured format .. do i need to install any plugin for this to work ?

  24. Hi,
    In My Company using netbeans 6.5 version FOR Developing Visual web based jsf applications…i’m a new to this IDE..How to improve my development activites..???.. …i’m unable to understand configurations like ApplicationBean,SessionBean,Requestbean…

  25. well tutorials are really very good but i want some more topics guide
    like
    ajax- drop down.
    file uploading – multiple and single,
    jsf mail sending,
    internationalization i18,
    caching

    could any one help me in this.

  26. I just started reading, I found many grammatical errors which make me wonder if I should go on. Simple reasons like this tells me if sample codes provided are in fact accurate as well or will just confuse me.

    1. I am not too concerned about grammar issues on a site like this. I am assuming that those that you found were there not because the lack of education, but because English is not the first language learned. I know several brilliant people that still struggle with a few of the English grammer. I am also glad to be recieving help from people around the world.

      I am looking more at the comments listed earlier for determining the relavance of this site. Read on within the comment list if you want to determine if this site is worth going on. I am looking more at this.

      Thanks very much mkyong

  27. i have some questions with language surpport when i use jsf2.0 ,can you tell me how to avoid gibberish when i use jsf2.0 process chinese?
    thank you very much,

  28. I have a jsp page which has dynamic includes. each dynamic include invoke its own backing bean and works fine with dataTables and reading data from backing bean, But i am facing problems with the command button. when i click command button, the control is not being transferred to the bean and it not navigating to the next page as it is not hitting the onclick method.

    any suggestion would be helpful. and also answer me how could we fix this problem if its a design issue.

    1. the buttons are in the data table?in case of command button we have to maintain the form tag very consciously. please place the command button in side the form.

  29. JSF+Spring+Hibernate

    Hi Mr. Yong,

    I am fully impressed by your passion and expertise in the areas you (or you guys) are providing the professional tutorials.

    Could you provide me the experience to create and maintain such a kind of website ? Don’t worry, my area is dealing in the area of science and Christian, such as 3+1 space and time, uncertainly in quantum mechanics, DNA innovation, math and science (theoretical physics, more specifically).

    Are u using JSF+Spring+Hibernate + MySQL integration or some more efficient way ?

    Thanks a lot in advance,

    Leo

      1. First I would like to thank for the wonderful tutorial you provided.

        I am facing bit problem with your chapter JSF + Spring integration, I had drill down a bit more by using the component library of primefaces.

        Problem:
        I had try to put a function or validator at the end of bean class used by the faces-config.xml. In place of authentication failed it should come back to jsf page but it’s currently going to spring section

  30. Thanks boss. The examples are good,easy and informative to start with. I even liked your Hibernate column. All examples are chossen exactly as what is required for a newbie to learn and implement. Thanks again for your effort. Keep posting. Godspeed.

  31. Great tutorial about JSF but can you help me what is that error mean and how can it solve it

    May 21, 2012 5:29:58 AM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Error configuring application listener of class org.apache.myfaces.webapp.StartupServletContextListener
    java.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3786)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

  32. i’m new in jsf2 and i got this error when i try to run my project can u help me plz

    SEVERE: Error configuring application listener of class com.sun.faces.config.ConfigureListener
    java.lang.NoClassDefFoundError: javax/faces/context/FacesContext

      1. this is my new error

        SEVERE: Error configuring application listener of class org.apache.myfaces.webapp.StartupServletContextListener
        java.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener

      2. I get this error now

        SEVERE: Error configuring application listener of class org.apache.myfaces.webapp.StartupServletContextListener
        java.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3786)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
        at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
        at org.apache.catalina.core.StandardService.start(StandardService.java:516)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

  33. Apparently you are an excellent teacher. I have not seen many people who can explain things in a simple clear fashion as you do here.

    It helped me a lot. If there is anything I can help, please let me know. Thanks,

  34. i want complete example about login and logout with session ID …. and how if i try to forward back make me logout or how can i handl forward and backword pages…. ?? plz

  35. Hi
    I’m desperately looking for help because to my knowledge I’m out of options.. I tried searching forums, google my problems with jsf2 but nothing fits to what I’m facing šŸ™‚
    I found Your blog very, if not the most inspiring during my search for tutorials with jsf2. From this place I’ve learned about configuration specifics necessary to set up development environment, which in my case is eclipse + tomcat 7. I managed to get some of Your code and made a few simple classes just to make myself understand this part of java world better… but here I ran into a problem, which made me stuck in one place.
    Here’s what I have:
    -Simple class in which arraylist of strings is initialized and filled with some static values.
    -Xhtml page, in which I have one column dataTable with a header.

    What I want is:
    -Make the mentioned class a managed bean, returning an arraylist.
    -Have the xhtml page with a dataTable filled with a content of an arraylist from managed bean.

    I know it sounds crazy to ask for such basics, but I had to cut down all my previous work to an atomic level, just to see where the problem lies.

    I made a class in a package called demo. The code of the class looks like below(it’s a simplified version of one oh Your examples):

    package demo;
    
    import java.util.ArrayList;
    import java.io.Serializable;
    
    import javax.annotation.PostConstruct;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.ViewScoped;
    
    @ManagedBean(name="userList")
    @ViewScoped
    public class UserList implements Serializable {
    	private static final long serialVersionUID = 1L;
    	private ArrayList<String> users;
    
    	@PostConstruct
    	public void create() {
    		users = new ArrayList<String>();
    		users.add("John");
    		users.add("Charley");
    		users.add("Priscila");
    		users.add("Kate");
    		users.add("Emily");
    		users.add("Barack");
    		users.add("Mia");
    		users.add("Arthur");
    	}
    
    	public ArrayList<String> getUsers() {
    		return users;
    	}
    }
    

    and the code of the xhtml file looks like this:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.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">
    <f:view>
    	<h:head>
    		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    		<title>User List 2</title>
    	</h:head>
    	<body>
    		<h:form>
    			<h:dataTable value="#{userList.getUsers}" var="user">
    				<h:column>
    					<f:facet name="header">User</f:facet>
    				</h:column>
    				<h:column>
    					<h:outputText value="#{user}" />
    				</h:column>
    			</h:dataTable>
    		</h:form>
    	</body>
    </f:view>
    </html>
    

    The problem is – I don’t get any output from the bean. What I get is just a column name.
    To be clear, I stayed away from touching faces-config.xml – this file has no entries besides it’s default content.

    My configuratoin seems to be ok and tomcat does not generate any exceptions nor any extra output during page start/refresh.
    I have all libs in place eg WebContent/WEB-INF/jstl-api and jstl-impl. Project Facets in project properties is checked and MyFaces are selected to be included in the application.

    Can You please help me?

  36. …please, am having a challenge with how to upload a file; I tried the examples given in the PrimeFaces documentation, yet, ActionListener event wont fire. Please, help me out. Below is the code:

    	<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" 
    		allowTypes="*.jpg;*.png;*.gif;" description="Images"/>		
    
    public class FileUploadController {
    	
    	private Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    
    	public void handleFileUpload(FileUploadEvent event) {
    		logger.info("Uploaded: {}", event.getFile().getFileName());
    
    		FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    		FacesContext.getCurrentInstance().addMessage(null, msg);
    	}
    }
    			
    
    1. Hi,

      I just found the solution for your problem. It took me days to found the solution because there isn’t any documentation :/

      You just need to include this in your web.xml:

      PrimeFaces FileUpload Filter
      org.primefaces.webapp.filter.FileUploadFilter

      PrimeFaces FileUpload Filter
      Faces Servlet

      Enjoy it! :p

      1. sorry about xml lol

        <filter>
        	<filter-name>PrimeFaces FileUpload Filter</filter-name>
        	<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
        </filter>
        <filter-mapping>
        	<filter-name>PrimeFaces FileUpload Filter</filter-name>
        	<servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
         
    2. hi i’m facing the primeface uploading problem.

      i have already written this also.

      PrimeFaces FileUpload Filter
      org.primefaces.webapp.filter.FileUploadFilter

      PrimeFaces FileUpload Filter
      Faces Servlet

      but the listener is not fired.
      please ASAp.. can you provide us a demo..wit spring 3+JSF 2.2+primeface 3.2

  37. I am hoping with your vast knowledge of JSF 2.0, you will be able to help.

    I am looking for a link / site where I can find out which all tags can make up a particular tag.

    For example, we can include a graphicImage tag in a commandLink tag.

    Is there a place where ALL JSF 2.0 tags and what other tags they can contain has been listed?

    Thank You,
    A B

  38. Hi all..
    It is good tutorial about jsf 2.0, but when i try to implements integrating JSF 2.0 with Spring JDBC, it appears an error like this. Anyone one knows how to fix this.? Thanks in advanced.

    javax.el.ELException: /page1.xhtml @16,8 value=”#{customer.getCustomerList()}”: java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:731)
    at javax.faces.component.UIData.getDataModel(UIData.java:1798)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
    at javax.faces.component.UIData.setRowIndex(UIData.java:473)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:662)
    Caused by: java.lang.NullPointerException
    at controller.CustomerBean.getCustomerList(CustomerBean.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:254)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:111)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    … 43 more

    1. “javax.el.ELException: /page1.xhtml @16,8 value=ā€#{customer.getCustomerList()}ā€:”

      i think u have to corrct this only

      plz change ‘#{customer.getCoustomerList()}’ to

      “#{customer.coustomerList}” if it is a private member or a public function in a customer bean class.

  39. Hello,
    require jsf tree example to list out a directory
    for eg: c:/downloads and all files and folders in it

  40. Hi,

    JSF 2 internationalization example work for only one page when user add more pages and click on other page it doesn’t work. when user select one language how it can b sett for all other pages?

  41. Hi,

    Very nice practicle tutorials. Can you please add JSF menue bar example it will really helpful for me as well as for others.

    Best Regards.

  42. Man, I would like to thank you for those amazing tutorials. I’ve been searching for this kind of information for a long time, but it doesn’t exists elsewhere, even in Mojarra or MyFaces sites. Most of information is not for newbies, they’re so technical…

    Thanks a lot, you have a new friend!

  43. thanks for all freamworks, it is perfect site that I have ever seen,but only there is no tutorial about the seam,if there is a tutorial about seam I will be so happyer more than as ever

    best regards

Leave a Comment

Your email address will not be published. Required fields are marked *