- 在web.xml中添加监听:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
或者
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
- 写一个静态方法:
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 获取 request
*/
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 获取 session
*/
public static HttpSession getSession(){
return getRequest().getSession();
}