Charles Morin
Charles Morin

Reputation: 1447

How to set an object in session and use it in all controllers?

I have a main Controller that acts as an entry point for my Spring MVC 4.0.3 application. The idea is to load the user from the database once, along with its profile (preferences), and then set them in session so they are easily re-used across the entire application.

I am pretty new to Spring MVC and I'm coming from Struts 1.3.5 in which I was used to do the following:

<bean define id="currentUser" name="currentUser"
             type="my.entity.bean" scope="session" />

I am using Thymeleaf for the frontend (views).

Is there any kind of AutoWiring possibility so it is automatically attached to all controllers without having to bring some boilerplate code everywhere?

Thank you for help.

Upvotes: 0

Views: 130

Answers (1)

JB Nizet
JB Nizet

Reputation: 692281

Define a CurrentUser Spring bean, with the scope "session", and inject it in all your controllers:

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CurrentUser {

    private UserInformation userInformation;

    public void setUserInformation(UserInformation userInformation) {
        this.userInformation = userInformation;
    }

    public UserInformation getUserInformation() {
        return userInformation;
    }
}

The "entry point" controller will set the user information, and the other ones will get it.

Beware of "entry points", though. Users should be able to bookmark any page and access your webapp without going through your entry point controller. An authentication filter or interceptor would be a better idea.

Upvotes: 2

Related Questions