用法: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 } }在web.xml增加如下代码:
<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>