Skip to content
javahacks.dev
JavaServer Faces

Fix ViewExpiredException in JavaServer Faces Applications

Fix ViewExpiredException in Faces by handling session timeouts with an error page, checking restarts and view limits, and choosing the right state saving.

7 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the OpenJDK, Vaadin, HTML5 and CSS logos.

A user leaves a form open over lunch, comes back, clicks Save and gets a stack trace:

Text
jakarta.faces.application.ViewExpiredException: viewId:/profile.xhtml - View /profile.xhtml could not be restored.

Nothing is wrong with the code. JSF keeps a server-side copy of every page it has rendered, so it can restore the component tree when the page is posted back, and that copy lives in the HTTP session. When the session times out, is invalidated, is lost in a restart or has pushed the oldest view out of a size-limited store, the copy is gone and the postback has nothing to restore. The exception is the framework telling you so. The question is how to handle it well. This post explains why the state disappears, then goes through five fixes in order of how often they are the right one: send the user somewhere useful, match the session to real usage, move state to the client, skip state where there is none to keep and survive restarts. Examples use Jakarta Faces 4.1 on Mojarra.

Why the state disappears

Four things remove a saved view, and each needs a different response.

CauseWhat happenedTypical sign
Session timeoutThe user was idle longer than the session timeout (default 30 minutes)Happens after a break, reproducible by waiting
Session invalidatedLogout in another tab, a security filter that renews the session, or a cookie that was clearedHappens right after a login or logout
View limit exceededThe session holds a bounded number of views (numberOfViewsInSession, default 15), and the oldest were evictedHappens after using Back or many tabs
Server restart or failoverThe session was in one node's memory and that node went awayHappens right after a deploy or on a cluster without session replication

To tell which one you have, compare the session id in the browser cookie (JSESSIONID) before and after the failure. A different value means the session itself is gone (timeout, invalidation, restart). The same value means the session survived and the view was evicted by the limit.

Fix 1: send the user somewhere useful

You cannot always prevent expiry, and a timeout is often correct behavior for a security reason. What you can do is stop showing a stack trace. Map the exception to a page that explains what happened and offers a way forward. In web.xml:

src/main/webapp/WEB-INF/web.xmlXML
<error-page>
    <exception-type>jakarta.faces.application.ViewExpiredException</exception-type>
    <location>/expired.xhtml</location>
</error-page>

A plain error page tells the user to go back and start again. A better handler redirects to the page they were on, with their intent preserved where possible. Write a custom exception handler that catches the exception and navigates:

src/main/java/dev/javahacks/web/ExpiredViewHandlerFactory.javajava
public class ViewExpiredExceptionHandler extends ExceptionHandlerWrapper {

    public ViewExpiredExceptionHandler(ExceptionHandler wrapped) {
        super(wrapped);
    }

    @Override
    public void handle() {
        var events = getUnhandledExceptionQueuedEvents().iterator();
        while (events.hasNext()) {
            Throwable t = events.next().getContext().getException();
            if (t instanceof ViewExpiredException vee) {
                FacesContext ctx = FacesContext.getCurrentInstance();
                try {
                    ctx.getExternalContext().getFlash().put("expired", true);
                    ctx.getApplication().getNavigationHandler().handleNavigation(ctx, null, "/login?faces-redirect=true");
                } finally {
                    events.remove();
                }
            }
        }
        getWrapped().handle();
    }
}

The handler is registered through an ExceptionHandlerFactory entry in faces-config.xml. The login page then reads the flash attribute and shows "Your session expired. Please sign in again." That small message turns a failure into a normal step. For AJAX requests, an error page redirect does nothing visible, because the response is a partial XML document; the exception handler above navigates through the Faces navigation handler, which does work for AJAX, since Faces emits a <redirect> in the partial response. The patterns behind the lifecycle that gets you here are in the JSF lifecycle explained.

Fix 2: match the session to the usage

If expiry is common because the timeout is shorter than the time users spend on a page, raise it. The session timeout is a property of the container:

src/main/webapp/WEB-INF/web.xmlXML
<session-config>
    <session-timeout>120</session-timeout>   <!-- minutes -->
</session-config>

A long timeout holds every idle session's memory for longer, including its saved views, so measure the cost before raising it: sessions times average session size times concurrent users. A better approach for long forms is to keep the session alive while the page is open with a lightweight periodic request that touches the session:

XML
<h:outputScript target="body">
    setInterval(function () { fetch('#{request.contextPath}/keepalive', {credentials: 'same-origin'}); }, 5 * 60 * 1000);
</h:outputScript>

with an endpoint at /keepalive that returns 204. This keeps the session as long as the page stays open and lets it expire once the tab is closed. Be deliberate: a keepalive defeats an idle timeout that exists for security, so do not use it on pages with sensitive actions. Raising or lowering numberOfViewsInSession and numberOfLogicalViews changes the view-limit case; the trade-off with memory is discussed in optimizing JSF performance and session size.

Fix 3: client state saving

Instead of keeping the view in the session, Faces can write the state into a hidden form field (jakarta.faces.ViewState) that the browser carries and returns on each postback. The server holds nothing, so there is nothing to expire:

src/main/webapp/WEB-INF/web.xmlXML
<context-param>
    <param-name>jakarta.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
</context-param>
<context-param>
    <param-name>org.omnifaces.CLIENT_STATE_TIMEOUT</param-name>
    <param-value>3600</param-value>
</context-param>

The costs are real. Every page is larger, because the state is in the HTML and in each request. The server pays CPU to serialize, encrypt and sign it. And the state must be protected from tampering: Mojarra encrypts it by default with a key generated at startup, which is a problem in a cluster, so configure a shared secret across nodes. With a restart or a second node, a different key makes old state unreadable, which produces the same exception. Client state saving also does not remove the session timeout for your own login state, so the user may still need to sign in again. Choose it when memory per session is the bottleneck and pages are small, not as a way to silence the exception.

Fix 4: skip the state where there is none to keep

Many pages do not need a saved view. A read-only page with navigation by links, a landing page, a report, a search result: none posts back. Mark them stateless and the problem cannot occur for them:

src/main/webapp/catalog.xhtmlXML
<f:view transient="true">
    <h:body>
        <h:outputText value="#{catalogBean.headline}" />
        <h:link outcome="product" value="Details">
            <f:param name="id" value="#{catalogBean.featuredId}" />
        </h:link>
    </h:body>
</f:view>

A transient view saves no state, so there is nothing to expire, and the user can leave the tab open for a week. Use GET navigation (h:link, h:button) from these pages; a command button that posts back to a stateless view fails. For forms that you do want stateful but that can be rebuilt, such as a login page, make the login form post to a servlet or a Spring Security filter, so it needs no JSF state. A user who opened the login page, waited an hour and submitted should not see an expiry error from the login form itself; this is a classic cause of complaints right after a timeout, because the login page's own view expired before the login was attempted.

Fix 5: survive restarts

A rolling deploy ends sessions held in the memory of the stopped node. If users hit ViewExpiredException after every deploy, either share sessions or avoid needing them. Two approaches:

Persist the session. Tomcat's PersistentManager or a Redis-backed session manager writes sessions to external storage, so another node can restore them. The saved views are serialized with the session, so every view-scoped bean in them must be Serializable; a bean that is not will fail at the point of replication with NotSerializableException, usually long after it was written. Keep session-scoped data small and serializable.

Use sticky routing and drain. A load balancer that pins a user to one node, with a drain period at deploy time, lets users finish their work on the old node before it stops. It reduces the problem without removing it.

If you deploy often, the cleaner design is to hold less in the session in the first place: keep entity ids and not object graphs in view beans, and let the stateless pages of fix 4 carry most of the traffic. The container and scope decisions that affect this are in JSF bean scopes explained.

Where this does not apply

If the exception appears immediately on the first click after the page loads, the session is not being kept at all: check that cookies are enabled and the JSESSIONID cookie is sent back (a proxy that strips it, or a Secure cookie on a plain HTTP connection, causes this). If it happens only in one browser tab after a login in another, you are seeing session renewal on authentication, which is a security feature and calls for the redirect handler in fix 1. For a deeper treatment of the whole framework, see the JSF and PrimeFaces guide, and the Mojarra settings are documented at Eclipse Mojarra with the contract in the Jakarta Faces specification.

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.