liveBook · Manning

Session scope

As explained in Spring Start Here, Second Edition

A session-scoped bean is a Spring-managed bean whose instance is shared across requests in the same HTTP session.

A session-scoped bean is managed by Spring and shared across requests in the same HTTP session. Spring creates a separate instance for each session, so different clients do not share the bean. section 9.2

Session scope is useful when an application needs to remember client-specific information across pages:

  • Keep a user’s login details available as they navigate the application, or retain products in a shopping cart. section 9.2
  • Keep stored data modest and avoid sensitive details. Concurrent requests from the same client can change the shared instance and cause race conditions. section 9.2

Remembering a logged-in user

Annotate a Spring-managed service with @SessionScope and store the username in it. After successful login, save the username; on later requests, check whether it is present before showing a protected page. section 9.2

Figure 9.9 A comparison between the request-scoped and session-scoped beans to help you visualize the differences between these two web bean scopes. You use request-scoped beans when you want Spring to create a new instance for each request. You use a session-scoped bean when you want to keep the bean (together with any details it holds) throughout the client’s HTTP session.

Compare request scope, which creates an instance for each request, with session scope, which retains one instance throughout the client’s session. section 9.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains per-session instance reuse and notes memory, sensitive-data, and concurrency concerns.
Examples
Uses a logged-in username as an example and names login state and shopping carts as use cases.
What you can do after
Apply it via Spring’s @SessionScope annotation to retain client-specific data across requests.
How it connects
Contrasts session scope with request scope and application scope, using HTTP sessions to share bean state across requests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.