JSF ManagedBean ManagedProperty With Examples

JSF ManagedBean is a java class that can be accessed by the JSF page for retrieving the values of the UI fields.

JSF ManagedBean

JSF Managed Bean can be created using @ManagedBean annotation. If a name attribute is not specified after the @ManagedBean annotation, it indicates that the name of the managed bean is the same as the class name. If the name is specified then it is a managed bean with the name specified in the attribute.

There are other annotations specifying the scope attributes which can be used with the managed bean.

@SessionScoped: Indicates that the bean is valid for the whole session

@RequestScoped: The bean is valid for the http request.

@ApplicationScoped: Bean is valid as long as the web application is valid.

Let’s now create a managed bean named Car.java as shown below.

In the above code, since we have not used any name attribute after @ManagedBean annotation, a managed bean with the name Car is created. @SessionScope is used to indicate that the bean is valid for the whole session. The Car bean basically contains the fields of the car like color, id, description, model and regno along with the getter and setter methods for these.

Now create viewdetails.xhtml which is the view for the details of the car.

Now run the application and it should produce the following output in the browser.


Injecting JSF Managed Bean

The @ManagedProperty annotation enables us to inject a managed bean into another managed bean. Let’s look into an example of how to inject the managed bean.

Create the managed bean named Car_gen.java as below.

Here the bean named alto_car is injected with the @ManagedProperty annotation. In the getter method we call the getDescription method of alto to fetch the value from the alto managed bean.

The #{alto_car} indicates that the managed bean named alto_car is injected as we have specified in the name attribute of @ManagedBean annotation in Alto.java class.

The “eager=true” indicates that the managed bean is created before it is requested for the first time.

Next create the bean named Alto.java as shown below.

This managed bean contains the description field with the value initialised and has getter and setter methods.

Now we create a JSF page named car_gen.xhtml to bind this.

We fetch the description value from the car_gen bean which further fetches the value from alto bean. This is possible because the Alto bean is being injected into the generic car_gen bean.

Upon running the code, we can see the JSF page rendering the description of alto car in the browser.


The final project structure is shown below.


You can download the project from below link and play around with it to learn more.

By admin

Leave a Reply

%d bloggers like this: