需求:
使用springMVC框架时,怎样在controller里获得Session。
一、如果需要把某个命令对象放到session里面,完全可以去类上加@SessionAttributes,但这只针对请求对象。二、如果我是在controller类里写的私有属性,那该如何去获取session,并把这个属性放到session里面,给其它方法共享呢?
解决:
(1)直接在方法上使用 HttpSession即可注入; 或者注入HttpServletRequest--->再获取Session
(2)官方文档说的很明白,有spring自动注入下面的东西,Requet,Response, Session,InputStream, OutputStream, Principal这些东西。
(3) 看代码
public static HttpSession getSession() {
HttpSession session = null;
try {
session = getRequest().getSession();
} catch (Exception e) {}
return session;
}
public static HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return attrs.getRequest();
}
通过上述两个方法获取,减少了方法中的参数个数