我正在尝试设置一个会话变量并在将来的请求中检索它。我看到在 Spring MVC 中有几种方法可以做到这一点。我尝试了几种方法,但没有一种方法有效。我回到最简单的方法(手动会话操作),仍然没有运气。
这是我的代码:
@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");
}
}
我在 /set 上访问我的服务器,然后在 /get 上。我查看我的日志并看到:
setting the session
and the userId is 'null' 'null'
为什么这不起作用?