Skip to content
javahacks.dev
JavaServer Faces

JSF Bean Scopes Explained With Examples and Pitfalls

Pick between request, view, session and application scope for a Faces bean, with an example of what goes wrong when the scope is too short or too long.

7 min read
Summarize in AI
Flat illustration of a Spring container wiring beans together, with the OpenJDK, Spring Boot, Spring, Apache Maven and JUnit5 logos.

Almost every Faces question about a value that vanishes, or a value that shows up in another browser tab, is a scope question. A scope is the lifetime of a bean instance: when the container creates it, how many users share it and when it is thrown away. Jakarta Faces 4 uses CDI for all of this. The old @ManagedBean annotations are gone, and the four scopes you use daily are CDI scopes, with @ViewScoped supplied by Faces itself.

This post takes each scope in turn with a small bean, the page that uses it and the failure that comes from choosing it badly. Then it covers what happens when scopes mix, and the serialization rule that causes deploy-time errors. The examples target Jakarta Faces 4 on Jakarta EE 10 or later; the Faces basics are in the JSF tutorial for beginners.

Request scope: one HTTP request

src/main/java/shop/web/SearchBean.javajava
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.util.List;

@Named
@RequestScoped
public class SearchBean {

    @Inject CustomerService customers;

    private String term;
    private List<Customer> results = List.of();

    public void search() {
        results = customers.findByName(term);
    }

    public String getTerm() { return term; }
    public void setTerm(String term) { this.term = term; }
    public List<Customer> getResults() { return results; }
}
src/main/webapp/search.xhtmlXML
<h:form>
  <h:inputText value="#{searchBean.term}"/>
  <h:commandButton value="Search" action="#{searchBean.search}"/>
  <h:dataTable value="#{searchBean.results}" var="c">
    <h:column>#{c.name}</h:column>
  </h:dataTable>
</h:form>

The container creates one SearchBean per HTTP request and drops it after the response is written. In the postback, Faces sets term, calls search() and renders the table in the same request, so everything lives long enough.

The failure comes the moment you add AJAX to the table, say <f:ajax execute="@this" render="table"/> on a sort link. The AJAX call is a new request, so a new SearchBean with term == null and an empty list, and the table the user was looking at turns blank. Request scope fits pages where a single request does all the work: search forms, login, confirmation pages.

View scope: one page, across postbacks

src/main/java/shop/web/CustomerEditBean.javajava
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.Serializable;

@Named
@ViewScoped
public class CustomerEditBean implements Serializable {

    @Inject CustomerService customers;

    private Long id;
    private Customer customer;

    public void load() {
        customer = customers.find(id);        // once, from a view parameter
    }

    public void save() {
        customers.update(customer);           // edited across several AJAX calls
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public Customer getCustomer() { return customer; }
}
src/main/webapp/customer.xhtmlXML
<f:metadata>
  <f:viewParam name="id" value="#{customerEditBean.id}"/>
  <f:viewAction action="#{customerEditBean.load}"/>
</f:metadata>

A view-scoped bean lives as long as the user stays on the same view, the same page posted back to itself. Every AJAX call, validation round trip and partial render reuses the same instance. Navigate to another view, or reload with a GET, and the bean is discarded. This is the right default for editing screens, paged and sorted tables and wizards on one page.

Two failures to know. First, a navigation outcome that changes the view id, or that ends with ?faces-redirect=true to the same page, creates a new bean; keep the user on the view for the whole interaction and pass identifiers with <f:viewParam>, as above. Second, view scope is stored in the session behind the scenes, keyed by a view state id, so a page left open in forty tabs holds forty copies. Faces limits this with jakarta.faces.NUMBER_OF_VIEWS_IN_SESSION and NUMBER_OF_LOGICAL_VIEWS, and the oldest view is evicted. A user who edits for an hour in one tab and then opens many others can find the first one throws ViewExpiredException, covered in fixing ViewExpiredException.

Session scope: the user

src/main/java/shop/web/UserSession.javajava
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.Locale;

@Named
@SessionScoped
public class UserSession implements Serializable {

    private String username;
    private Locale locale = Locale.ENGLISH;

    public boolean isLoggedIn() { return username != null; }
    // getters, setters
}

One instance per HTTP session, shared by every tab and window that user has open. It suits identity, language, a shopping cart and little else.

The classic failure is form state. If CustomerEditBean above were session scoped, two tabs editing customers 12 and 14 would share one customer field, and the user would save customer 14's changes into customer 12 without any error. The second failure is memory. Every user holds every session bean until the session times out, so 5,000 users with a 400 KB session bean each is 2 GB of heap that nobody is looking at. Keep session beans small and holding identifiers, not object graphs.

Application scope: everyone

src/main/java/shop/web/CountryList.javajava
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Named;
import java.util.List;

@Named
@ApplicationScoped
public class CountryList {

    private List<String> countries;

    @PostConstruct
    void init() {
        countries = List.copyOf(loadFromDatabase());     // read once, immutable
    }

    public List<String> getCountries() { return countries; }
}

There is one instance for the whole application, created on first use and shared by all threads. It suits lookup data, configuration and caches. The rule is that it must be thread safe: either immutable after construction, as above with List.copyOf, or guarded. A field like private Customer current in an application-scoped bean is shared by every user at once, and the bug looks like one customer seeing another's data. The same rule drives safe sharing between threads.

Choosing, as a table

ScopeAnnotationLifetimeShared bySerializable?Use it for
Request@RequestScopedOne HTTP requestNobodyNoSearch forms, login, one-shot actions
View@ViewScopedWhile the user stays on one viewOne browser tabYesEditing, AJAX tables, wizards on a page
Session@SessionScopedUntil the session endsAll of a user's tabsYesIdentity, locale, cart
Application@ApplicationScopedThe whole deploymentEvery userNoReference data, configuration, caches
Dependent@DependentThe life of its ownerThe injecting beanFollows the ownerHelpers with no state of their own

Faces adds @FlowScoped for multi-page flows that end at a defined exit, and CDI adds @ConversationScoped, which you start and stop yourself. Both exist for the case "longer than a view, shorter than a session". If you reach for session scope to carry data across three pages, a flow is the tool.

Injecting across scopes

A longer-lived bean can hold a shorter-lived one, because CDI injects a proxy, not the instance. An @ApplicationScoped service can safely inject @RequestScoped context, and every call is routed to the instance for the current request:

java
@Named
@ApplicationScoped
public class AuditService {

    @Inject RequestInfo requestInfo;      // request scoped: a proxy, resolved per call

    public void record(String action) {
        log(requestInfo.userAddress(), action);
    }
}

The reverse is the trap, though only in a narrower sense. A request-scoped bean that holds a reference to a shorter object is fine, but a long-lived bean must never copy mutable request data into its own fields: this.lastSearch = searchBean.getTerm() in an application bean stores one user's text where all users read it. Pass data as method arguments, not as fields.

Passivation and the Serializable rule

Session and view scopes are passivating: the container may write the instance to disk or send it to another node, for example in a cluster, or when memory is short. For that to work, the bean and everything it references must implement Serializable. A bean that does not fail in one of two ways. With strict validation the deployment fails at startup with WELD-001413-style messages about a passivation-capable bean that has a non-serializable dependency, which is the kind. Without it, the failure happens later: NotSerializableException at the first passivation, usually at 3 a.m. during a rolling restart.

Mark unserializable fields transient, and inject services as @Inject fields on the bean, because CDI proxies of injected beans are serializable:

java
@Named
@ViewScoped
public class ReportBean implements Serializable {

    @Inject ReportService service;            // fine: injected proxy
    private transient java.sql.Connection c;  // never serialized; reopen when needed
}

Where this does not apply

If your Faces application is stateless, with every page a GET and an action that redirects, almost any scope works and request scope is correct. If the application is fronted by many server nodes without sticky sessions and without session replication, session and view scope will lose state on a node switch; either enable replication or store the state outside the session. For the larger picture of how a Faces page is built, see the JSF and PrimeFaces guide. The scope definitions are in the Jakarta CDI specification, and the Jakarta EE tutorial covers the Faces lifecycle.

Also inJakarta EE
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.