HttpContext.Current.Session equivalent in Spring MVC

2.5k Views Asked by At

I'm an asp.net developer and I'm now working on a Spring MVC webproject.

I want to write a helper class that allows me to get the current User or check if a user is logged in, something like that.

In asp.net I could create a class anywhere in my project and for accessing the current session for a request I could write HttpContext.Current.Session["CurrentUser"].

What is the way to do this in Spring MVC?

I found this Blogpost, saying that this is not possible (here). But I also found this stackoverflow post, where the method of getting the current session looked pretty similar to the asp.net way (here). It didn't work for me though.

1

There are 1 best solutions below

0
On

In Spring MVC/Spring Security you can make use of the AuthenticationPrincipal annotation which resolves given argument to the current authenticated user.

@RequestMapping("/user")
public String show(@AuthenticationPrincipal CustomUser customUser) {
    // do something with CustomUser
    return "view";
}

Under the hood current authentication is fetched from the SecurityContext:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

You can use SecurityContextHolder to retrieve current authentication anywhere in your code. But keep it to a bare minimum in order to keep clarity and testability high.

If you want to retrieve or write data from/to the current http session just instruct Spring MVC to give it to you:

@RequestMapping("/user")
public String show(HttpSession session) {
    // do something with session data
    session.getAttribute("myAttr");
    return "view";
}

If you want to save data in the session for several request, for instance a wizard, you can leverage Spring's so called SessionAttributes.