From the course: Java EE: JavaServer Faces JSF

What are managed beans?

From the course: Java EE: JavaServer Faces JSF

Start my 1-month free trial

What are managed beans?

- [Instructor] The textbook definition of a managed bean is simply a Java class inside a container that the developer doesn't have to instantiate manually. Simply put, it's the plain Java code that sits behind a JSF page. Let's examine the plain Java code that powers our JSF webpage. Let's visit this bean from earlier. We started with a standard Java class, and added some methods to execute business functionality, but really, what makes this a JSF-managed bean? Let's start with the beans.xml file. This file is from the Context and Dependency Injection (CDI) form. It's the file that powers all managed beans in JSF. Without it, the JSF runtime won't recognize our POJOs as managed beans. Having created the beans.xml file, our WelcomePageBean class is automatically registered with the CDI runtime as a managed bean. We then added JSF and CDI annotations to the class. This is where things get really JSF-like. The @Named annotation on line 15 gives a name or a handle that we can use to refer to this managed bean from our JSF page. Using this name, WelcomePageBean that we supplied to the @Named annotation, we can refer to Java bean properties on our managed bean from our index.xhtml file. As a rule, only fields that are properly encapsulated with a getter and setter pair can be accessed from the XHTML file. Next we have the @RequestScoped annotation on line 16. This annotation and others like it stipulate to the CDI runtime how long this managed bean, WelcomePageBean, should live, that is its scope. For now, let's know that the @RequestScoped annotation here stipulates that an instance of the WelcomePageBean should be created whenever a page needs it, and it's automatically destroyed whenever the page has completely loaded in the browser. And that's it. We have a functional managed bean. Let's recap what we need to create a managed bean. First we need to have our beans.xml file, just one for the entire application inside the web-inf folder. Next, we need our plain old Java object, or POJO, with the necessary Java bean conventions in play. Then we name the bean with the @Named annotation. And then finally, we define the scope of the managed bean with an @RequestScoped annotation. In JSF, the types of managed beans available are marked by how long they live, or to put it another way, when the CDI context instantiates or destroys a managed bean. This concept of the lifespan of a managed bean is known as the scope of the managed bean. There are seven general scopes of managed beans, but we'll only be going through the five pertinent ones to JSF. We'll examine the application scoped, session scoped, RequestScoped, and ViewScoped annotations in great detail. The FlashScope we'll cover in brief.

Contents