Home >Java >javaTutorial >Spring ordinary classes obtain session and request objects
When using spring, it is often necessary to obtain session and request objects in ordinary classes.
For example, some AOP interceptor classes, when using struts2, because struts2 has an interface, you can easily get the session object using org.apache.struts2.ServletActionContext.
Usage:
ServletActionContext.getRequest().getSession();
In the ordinary classes of traditional java spring projects, how to obtain session and request?
1. Add the following code to web.xml:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
2. You can directly inject session and request in ordinary classes
@Autowired private HttpSession session; @Autowired private HttpServletRequest request;
In addition, in After the Listener in the first step, you can also use code to obtain the reuqest object:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
If you are in a spring boot project and there is no web.xml, you do not need to manually register the Listener in the first step. You can directly Inject session and request in ordinary classes.
The above is the detailed content of Spring ordinary classes obtain session and request objects. For more information, please follow other related articles on the PHP Chinese website!