Home  >  Article  >  Java  >  Spring ordinary classes obtain session and request objects

Spring ordinary classes obtain session and request objects

(*-*)浩
(*-*)浩forward
2019-08-31 15:07:382032browse

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.

Spring ordinary classes obtain session and request objects

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:


        org.springframework.web.context.request.RequestContextListener

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete