The Java EE 6 Tutorial, Volume I

Developing a Backing Bean

In a typical JavaServer Faces application each page in the application connects to a backing bean (a type of managed bean). The backing bean defines the methods and properties that are associated with the components.

The following managed bean class,, generates a random number between 0 and 10:

package guessNumber;

import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped; 

public class UserNumberBean {
    Integer randomInt = null;
    Integer userNumber = null;
    String response = null;
    private long maximum=10;
    private long minimum=0;

    public UserNumberBean() {
        Random randomGR = new Random();
        randomInt = new Integer(randomGR.nextInt(10));
        System.out.println("Duke's number: " + randomInt);
    public void setUserNumber(Integer user_number) {
        userNumber = user_number;

    public Integer getUserNumber() {
        return userNumber;

    public String getResponse() {
        if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0))
            return "Yay! You got it!";
            return "Sorry, " + userNumber + " is incorrect.";

    public long getMaximum() {
        return (this.maximum);

    public void setMaximum(long maximum) {
        this.maximum = maximum;


    public long getMinimum() {
        return (this.minimum);

    public void setMinimum(long minimum) {
        this.minimum = minimum;


Note the use of the @ManagedBean annotation which registers the backing bean as a resource with JavaServer Faces implementation. The @SessionScoped annotation registers the bean scope as session.