JSF 2.2 Managed Beans

 

In a JSF 2.2 application, the managed bean plays both the role of controller and model.

In this example, we will see two ways to create and configure managed beans in an application.

 

1. Technologies used

  • JSF 2.2.8
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

JSF2.2-Managed-Beans-1

 

3. Project dependencies

 

4. User class

In this example, we will use the following  Java class as a managed bean :

 

5. Using XML configuration

This approach consists of declaring and configuring our bean in the JSF configuration file :  faces-config.xml.

And we have to declare the faces-config.xml in the web.xml file :

 

So at application startup, the User bean will be instantiated and stored in the  session scope.

 

6. Using annotation

We have simply to annotate our User class by @ManagedBean

We have defined the scope in which the managed bean will be stored.

We used optionally the name attribute to specify the name with which the managed bean will be registered. When it is not used, the managed bean is registered with the class name (user).

 

7. JSF page

File : index.xhtml

 

8. Test It

URL : http://localhost:8080/JSF2.2-Managed-Beans/

 JSF2.2-Managed-Beans-2

 

Download source code

  • Dear Walid,

    I saw your all article, i found it very comprehensive and easy.

    May Allah swt bless you for this sharing and helping.

    Thanks

    • Walid RAHALI

      You’re welcome :)

  • Torin Walker

    Walid,

    Just wondering – I have an “authBean” that handles the login page, and right after deployment, it works perfectly… but after some time, and I can’t pinpoint when or why to a specific line in the server’s log, the EntityManager I am calling in this authBean suddenly becomes null.

    Now it is my understanding that putting the annotation @ManagedBean in the class makes it an application-managed bean, and my @PersistenceContext EntitityManager em; should be automatically populated.

    So, my question is, is it necessary to put each bean into the managed-bean.xml if it is already annotated in the class?