Question

I'm new to JSF and was wondering:

If I have a controller that handles all the work for a given page and a bean that holds all the data for said page, is It necessary to have both the

@ManagedProperty(value="#{myBean}") 

annotation on the controller and the

@ManagedBean(name="myBean")
@SessionScoped

annotations on the form bean?

Was it helpful?

Solution

Managed beans in JSF are used to store the state of a web page. The JSF implementation is responsible for creating and discarding the bean objects( hence the name managed bean).

For every class you write @ManagedBean, the bean object is created by the JSF implementation as and when it detects an usage of the bean with the name(you can either sepcify a bean name or leave it to JSF to use the default name-class name with the first character changed to lowercase). The object created is placed in a map of the specified scope. Each scope has a map that it uses to store bean objects which have that scope specified.

Now if you need the values of these beans in your controller, you have to inject it using the ManagedProperty annotation. Note that you would need to provide the controller with a setter method for the managedProperty.

So to answer your question, the managedBean annotation is required to tell the JSF implementation to manage the bean instance and store the values in the table specific to the session scope. And the ManagedProperty annotation is needed to use that bean stored in the current session so that you can access all of its values.

OTHER TIPS

We use @ManagedBean annotation to register a java bean with a JSF framework. This is a replacement for a faces-config.xml <managed-bean> element. We typically do not use name attribute because it already defaults to a simple class name camel cased.

We use @RequestScope and other scope annotations to explicitly specify the scope we want via annotation. This is equivalent to specifying<managed-bean-scope> xml entry. If you don't specify the scope it will be defaulted to @NoneScoped.

We use @ManagedProperty and specify an EL-expression in its value attribute to use JSF-provided dependency injection engine for JSF artifacts like other managed beans with broader scopes and EL-defined variables like param. We do it in case we need the injected values in other JSF artifacts, most typically beans. The injected values are available in bean's @PostConstruct-annotated method. This is an alternative to <managed-property> xml entry.

To sum it up. Use @ManagedBean @RequestScoped to register a bean with JSF framework. Use @ManagedProperty inside this bean to be able to reference among others other JSF beans with the same or broader scopes in this bean. In case you don't need to reference other beans in the created bean you don't need to use the @ManagedProperty annotation as it's purely optional.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top