Tagged: jsf2

Learning JSF2: Managed beans

I’m starting a series called Learning JSF 2 on my blog. It will cover JSF 2 with emphasis on new features. Every post will cover a different features, the first one covers managed beans.

Managed bean is a regular Java bean with a fancy name. When we register the bean with JSF it becomes a managed bean, in other words, it’s now managed by the framework (JSF). In JSF, managed beans are used as model for UI components. In JSF 1.2, for a bean to become a managed bean, you had to register it in JSF configuration file such as faces-config.xml. One of the biggest announces was that as the number of beans grew, the JSF configuration file grew as well, and it was difficult to keep track of all names annd changes in three different files that all were “connected” (JSF configuration file, the JSF view and the bean itself).

Luckily, JSF 2 team has introduced annotations to register managed beans. With annotations, the bean and its registration are in the same place (Java class) so it becomes much easier to manage. You can still use JSF configuration file to register managed beans, and in some cases as you will see it’s the only way. Let’s start.

Basic Configuration

In JSF 1.2, the simplest registration looks like this:

<managed -bean>
  </managed><managed -bean-name>userBean</managed>
  <managed -bean-class>example.UserBean</managed>
  <managed -bean-scope>request</managed>

Exactly the same registration in JSF 2 looks like this:

package example;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
 
@ManagedBean(name="userBean")
@RequestScoped
public class UserBean {
 
   private String name;
 
   public String getName() {
	return name;
   }
   public void setName(String name) {
	this.name = name;
   }
   public UserBean() {}
}

Continue reading