在使用spring时,经常需要在普通类中获取session,request等对像.
比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts2.ServletActionContext即可很方便的取到session对像.
在web.xml增加如下代码:
本文转载于:http://blog.csdn.net/chenzenan/article/details/25387977
比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts2.ServletActionContext即可很方便的取到session对像.
用法:ServletActionContext.getRequest().getSession();
但在单独使用spring时如何在普通类中获取session,reuqest呢?
第一种:
在web.xml增加如下代码:
- <listener>
- <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
- </listener>
注解方式
- @Autowired
- private HttpSession session;
- @Autowired
- private HttpServletRequest request;
- HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
第二种:
- public class RequestUtils {
- private static final Logger log = LoggerFactory
- .getLogger(RequestUtils.class);
- private static ThreadLocal<HttpServletRequest> requestLocal= new ThreadLocal<HttpServletRequest>();
- public static HttpServletRequest getRequest() {
- return (HttpServletRequest)requestLocal.get();
- }
- public static void setRequest(HttpServletRequest request) {
- requestLocal.set(request);
- }
- }
- public class GetRequest implements Filter {
- /**
- * Default constructor.
- */
- public GetRequest() {
- // TODO Auto-generated constructor stub
- }
- /**
- * @see Filter#destroy()
- */
- public void destroy() {
- // TODO Auto-generated method stub
- }
- /**
- * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
- */
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- // place your code here
- RequestUtils.setRequest((HttpServletRequest)request);
- // pass the request along the filter chain
- chain.doFilter(request, response);
- }
- /**
- * @see Filter#init(FilterConfig)
- */
- public void init(FilterConfig fConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
- <filter>
- <filter-name>GetRequest</filter-name>
- <filter-class>com.filter.GetRequest</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>GetRequest</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>