How to get session and request objects in common classes of spring

When using spring, it is often necessary to obtain session, request and other objects in ordinary classes. For
example, some AOP interceptor classes, when struts2 is used, because struts2 has an interface, it is very convenient to use org.apache.struts2.ServletActionContext Get the session object.
Usage: ServletActionContext.getRequest().getSession();
But how to get the session and reuqest in the ordinary class when using spring alone?
In fact, there is a way.
First, add the following code to web.xml :
  <listener>
         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

Then in normal bean class:




[html] view plaincopy
01.@Autowired 
02.private HttpSession session; 
03. 
04.@Autowired 
05.private HttpServletRequest request; That 




's it, is it very convenient to use the session object in the class. The
reason why I want to write it is because the current usage of this online is all using Why write a lister and save the session, it's too troublesome.
Spring is such a powerful framework, of course, they have already thought of it. That's why we have such a convenient way to use it.







After adding the above listener, you can also use code to get reuqest objects like

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder. getRequestAttributes()).getRequest();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326642285&siteId=291194637
Recommended