Search code examples
springexceptionspring-mvchttpsessionrequired

can't store parameter in session (Spring MVC)


I have the following problem with annotation based Spring MVC:

I have two Controllers (LoginController, AdminController) and I can pass an object (loggedInUser of type BonjourUser) form the LoginController to the AdminController by persisting it in the session. So far so good.

To prevent hotlinking, on the initial "GET" the AdminController verifies it received a valid admin-user when it is called. This works fine the first Time, because the loginController added the object to the session.

Now here comes my problem: Once the admin has logged in and tries to reaccess the admin-page (eg via a link in the JSP) the user-object seems to have vanished from the session, for I get a HttpSessionRequiredException for the "loggedInUser" attribute. AFAIK the object should not be removed from the session unless I call setComplete() on the session. (I am not calling this method!) So why is the attribute removed from the session? I read here that you cannot pass session attribues between controllers. But then here it is said that it is possible. I also think it should work, since I already pass a parameter between controllers, when I redirect from the LoginController to the AdminController.

So here is the code:

LoginController:

@Controller
@SessionAttributes("loggedInUser")
public class LoginController extends BonjourController
{
    [...]

    @RequestMapping(value = {"/home"}, method = RequestMethod.POST)
    public String validate(@ModelAttribute(value = "command") BonjourUser user, ModelMap map, HttpSession session)
    {
        [...]
        map.addAttribute("loggedInUser", loggedInUser);

        [...]
        return "redirect:/admin";
    }
}

And the AdminController:

@Controller
@RequestMapping(value = "/admin")
@SessionAttributes("loggedInUser")
public class AdminController extends BonjourController
{
    @RequestMapping(method = RequestMethod.GET)
    public String loginAdmin(@ModelAttribute("loggedInUser") BonjourUser loggedInUser, ModelMap map, HttpSession session)
    {
        //check if access is authorized
        if(loggedInUser == null)
        {
            return "redirect:/login";
        }

        [...]
    }
}

The link I use in the admins' jsp (which leads to the exception) looks like this

<a href="admin">Once more to admin section</a>

Basicaly I get the same exception when I just enter this in my browsers URL-bar:

http://localhost:8080/Bonjour/admin

The exception looks like this:

org.springframework.web.HttpSessionRequiredException: Expected session attribute 'loggedInUser'

So what do I need to change to ensure the user-object (loggedInUser) is not removed from the session?

Thanks in advance,

Maex


Solution

  • My bad - I blocked cookies!

    So the session had no chance to be persisted except for POST requests, therefor the login worked but the GET for the same page did not...