SpringMVC中使用@SessionAttributes获取session的小问题

Srpingmvc使用@SessionAttributes获取session的问题

一、背景:

Springmvc中有很多中方式获取设置Session,有原始的HttpSession,有通过HttpServletRequest间接设置获取session,也有Springmvc独有的注解方式@SessionAttributes(value = "resident")方式设置session。

我在项目中使用了注解的方式设置Session,采用ModelMap的形式设置Session,这里没有问题,但是当我从另一个Controller中打算获取Session的时候出现了问题,一开始,我是用的@ModelAttribute("resident") Resident resident的方式获取对应的对象,但失败了,获取到的值为null。

我看了网上的答案,五花八门,有的在某篇博客中可以的获取方式,在另外的博客中又变得不可以。因此也是一脸懵逼,好在我还是很有耐心的。最终也解决了如何获取@SessionAttributes(value = "resident")注解形式所设置的session。


二、解决方案:

使用HttpServletRequest类,通过request间接获取session,然后获取其中的键值。


三、测试代码:

1
2
3
4
5
6
7
8
9
10
11

@RequestMapping(value = "/index")
public String entr_index(@ModelAttribute("resident") Resident resident, HttpServletRequest httpServletRequest){
HttpSession session = httpServletRequest.getSession();
Resident residents = (Resident) session.getAttribute("resident");
System.out.println(residents.getPassword()); // 分别测试HttpServletRequest和ModelAttribute
System.out.println(resident.getPassword());
return "index";
}


运行结果:

44eb5b04af14d5b07c446ff9c6f1d403 这是通过HttpServletRequest的实例获取的session值

null 这是通过@ModelAttribute获取的session值,获取不到

至于其他设置获取session的方法,等我以后用到了,再做记录。