I am trying to set a session variable and retrieve it on a future request. I see there are several ways to do this in Spring MVC. I have tried several ways but none of them are working. I went back to the simplest way (manual session manipulation) and still no luck.
Here is my code:
@Controller
public class Test {
private static final Logger LOG = Logger.getLogger(Test.class);
@RequestMapping({ "/set", "/set/" })
public final ModelAndView set(
final HttpServletRequest request,
final HttpServletResponse response,
final HttpSession session) {
LOG.info("setting the session");
session.setAttribute("userId", new Object());
request.getSession(true).setAttribute("userId", new Object());
return new ModelAndView("someView");
}
@RequestMapping({ "/get", "/get/" })
public final ModelAndView get(
final HttpServletRequest request,
final HttpServletResponse response,
final HttpSession session) {
final HttpSession session1 = request.getSession();
final Object userId = session.getAttribute("userId");
final Object userId1 = session1.getAttribute("userId");
LOG.info("and the userId is '" + userId + "' '" + userId1 + "'");
return new ModelAndView("someView");
}
}
I hit my server at /set, then at /get. I look at my logs and see:
setting the session
and the userId is 'null' 'null'
Why is this not working?
I don’t know why, but putting the following in my web.xml fixed the problem: