In JSF applications, Java beans are the conduits between the user interface and the back end of the application. A Java bean is a class that exposes properties and events to an environment such as JSF. They are named and can have different scopes or lifetimes according to the needs of the application.
package com.corejsf; import java.io.Serializable; import javax.inject.Named; import javax.enterprise.context.SessionScoped; @Named("user") @SessionScoped public class UserBean implements Serializable { private String name; private String password; // Defines read/write bean property user.name. public String getName() { return name; } public void setName(String newValue) { name = newValue; } // Defines read/write bean property user.password. public String getPassword() { return password; } public void setPassword(String newValue) { password = newValue; } }
The user bean is given its name by the following Java annotation.
@Named("user")
The user bean is given a session scope by the following Java annotation.
@SessionScope
Among the scopes that can be declared are:
Short-lived; new instance created with each request.
Not appropriate if data is to persist beyond the request.
Lasts during repeated connections by the same client.
Session tracking usually done with cookies, otherwise through URL rewriting and session IDs.
Lasts for duration of the web application.
Shared among all requests and all sessions.
The user bean has two read/write properties user.name and user.password. The properties are defined by implementing appropriately named getter and setter methods.
// Defines read/write bean property user.name. public String getName() { return name; } public void setName(String newValue) { name = newValue; } // Defines read/write bean property user.password. public String getPassword() { return password; } public void setPassword(String newValue) { password = newValue; }
A property is a named value of a given type that can be read and/or written
Properties are defined using the get/set convention, with the first letter of the property name changed to upper case