问题描述
使用springMVC框架时,怎样在controller里获得Session。一、如果需要把某个命令对象放到session里面,完全可以去类上加@SessionAttributes,但这只针对请求对象。二、如果我是在controller类里写的私有属性,那该如何去获取session,并把这个属性放到session里面,给其它方法共享呢?
解决方案
直接在方法上使用 HttpSession即可注入; 或者注入HttpServletRequest--->再获取Session
解决方案二:
其实你遇到问题的时候可以看看官方的文档:http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-arguments官方文档说的很明白,有spring自动注入下面的东西,Requet,Response, Session,InputStream, OutputStream, Principal这些东西。Request or response objects (Servlet API). Choose any specific request or response type, for example ServletRequest or HttpServletRequest.Session object (Servlet API): of type HttpSession. An argument of this type enforces the presence of a corresponding session. As a consequence, such an argument is never null.[Note]NoteSession access may not be thread-safe, in particular in a Servlet environment. Consider setting the RequestMappingHandlerAdapter's "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently.org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver in a Servlet environment.java.io.InputStream / java.io.Reader for access to the request's content. This value is the raw InputStream/Reader as exposed by the Servlet API.java.io.OutputStream / java.io.Writer for generating the response's content. This value is the raw OutputStream/Writer as exposed by the Servlet API.java.security.Principal containing the currently authenticated user.
解决方案三:
HttpSession作为参数即可
解决方案四:
例如一个Controller中的一个getUser的方法.public String getUser(HttpSession httpSession,其他参数){ 在方法里面就可以使用session了。}
解决方案五:
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();}通过上述两个方法获取,减少了方法中的参数个数
解决方案六:
把HttpSession放到controller中的方法中去,做为请求参数。