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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: alkaline water benefits()

  • Pingback: water ionizer()

  • Pingback: lan penge nu sms()

  • Pingback: fue()

  • Pingback: stop parking()

  • Pingback: best DIRECTV deals()

  • Pingback: tvpackages.net()

  • Pingback: tvpackages.net()

  • Pingback: best online casinos()

  • Pingback: vpn service 2015()

  • Pingback: kangen water()

  • Pingback: alkaline water()

  • Pingback: water ionizer()

  • Pingback: watch free movies online()

  • Pingback: stream movies()

  • Pingback: watch movies online free()

  • Pingback: how to loose weight()

  • Pingback: Blue Coaster33()

  • Rakesh

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

  • Abdul

    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

  • Ashwin

    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.

  • Pingback: JSF odkazy | BRAIN SNIPPETS()

  • souvik

    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 ?

  • http://javadomain.in Diva

    you can find some more details in the below link,”http://javadomain.in/hello-world-jsf-example-steps/”

  • Mohan

    Hi Mkyong,

    No words to express. it’s reallhy awesome.

    thank you very much!!!!

  • Howard

    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! :)

  • Fareed Mohammed

    this is always best choice to start any java related stuff with this website

    keep posting Thanks !…

  • Fareed Mohammed

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

    Thanks Q very much

  • http://www.refisoft.blogspot.com Mohamed Rafeeque

    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

  • Rohan

    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.

  • http://www.zxuqian.com Xuqian

    Nice tutorial, got it! Thank you!

  • Venkat

    hi,

    how to configure jsf+jpa please can you guide me

    Thanks in advance

    Venkat

  • rahul

    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.

  • chanakyan xavierrajan

    Really helpful.

  • Luis

    I like this tutorial.
    A good job.
    Thanks

  • sridhar

    How can i zoom an image using jsf with ajax?

  • shareef

    i love the common errors parts so cool please add every thing always :)

  • Vanderson

    Thanks for your post(tutorial), very good for my work.

  • Pingback: Rational Software Architect 8.5′daki JSF2.0 projesine jQuery ile ipucu kutucu?u(tooltip) eklemek | lafefeleri.com()

  • Pingback: Rational Software Architect 8.5′daki JSF2.0 projesine jQuery ile ipucu kutucu?u(tooltip) eklemek | lafefeleri.com()

  • Eva

    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>
  • Eva

    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.

  • Ashim

    how Integrate JSF 2.0 with Zk framework

  • Amy

    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.

  • Dominic N

    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

  • mohiadeen

    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 ?

  • Lakshmi

    How to create charts using JSF2.0?

    • lucaster

      Have a look at the PrimeFaces library

  • Lakshmi

    can u please suggest me which is the best framework for web development among JSF2.0,Struts2 & Wicket 1.6…