使用springMVC框架时,怎样在controller里获得Session。

使用springMVC框架时,怎样在controller里获得Session。
一、如果需要把某个命令对象放到session里面,完全可以去类上加@SessionAttributes,但这只针对请求对象。
二、如果我是在controller类里写的私有属性,那该如何去获取session,并把这个属性放到session里面,给其它方法共享呢?

6个回答

直接在方法上使用 HttpSession即可注入; 或者注入HttpServletRequest--->再获取Session

jinnianshilongnian
jinnianshilongnian en
6 年多之前 回复
xiaoxing598
TerrenceTian private void cleanSession(HttpServletRequest request){}像这里吧,张老师!
6 年多之前 回复

把HttpSession放到controller中的方法中去,做为请求参数。

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();
}
通过上述两个方法获取,减少了方法中的参数个数

例如一个Controller中的一个getUser的方法.
[code="java"]public String getUser(HttpSession httpSession,其他参数){
在方法里面就可以使用session了。
}[/code]

HttpSession作为参数即可

其实你遇到问题的时候可以看看官方的文档:[url]http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-arguments[/url]
官方文档说的很明白,有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] Note
Session 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.

asialee029
asialee029 RequestMappingHandlerAdapter的配置呀
6 年多之前 回复
xiaoxing598
TerrenceTian Consider setting the RequestMappingHandlerAdapter's "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently. 这是要到哪里设置,来确保session是线程安全的呢?
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!