普通類中獲取request,session
阿新 • • 發佈:2019-02-17
在使用spring時,經常需要在普通類中獲取session,request等對像.
比如一些AOP攔截器類,在有使用struts2時,因為struts2有一個介面使用org.apache.struts2.ServletActionContext即可很方便的取到session對像.
比如一些AOP攔截器類,在有使用struts2時,因為struts2有一個介面使用org.apache.struts2.ServletActionContext即可很方便的取到session對像.
用法:ServletActionContext.getRequest().getSession();
但在單獨使用spring時如何在普通類中獲取session,reuqest呢?
第一種:
在web.xml增加如下程式碼:
- <listener>
-
<listener-class
- </listener>
註解方式
- @Autowired
- private HttpSession session;
- @Autowired
- private HttpServletRequest request;
-
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
第二種:
- publicclass RequestUtils {
- privatestaticfinal Logger log = LoggerFactory
- .getLogger(RequestUtils.class);
- privatestatic ThreadLocal<HttpServletRequest> requestLocal= new ThreadLocal<HttpServletRequest>();
-
publicstatic HttpServletRequest getRequest() {
- return (HttpServletRequest)requestLocal.get();
- }
- publicstaticvoid setRequest(HttpServletRequest request) {
- requestLocal.set(request);
- }
- }
- publicclass GetRequest implements Filter {
- /**
- * Default constructor.
- */
- public GetRequest() {
- // TODO Auto-generated constructor stub
- }
- /**
- * @see Filter#destroy()
- */
- publicvoid destroy() {
- // TODO Auto-generated method stub
- }
- /**
- * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
- */
- publicvoid 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)
- */
- publicvoid 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>