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

Spring ordinary classes obtain session and request objects

(*-*)浩
Release: 2019-08-31 15:07:38
forward
2204 people have browsed it

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();
Copy after login

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>
Copy after login

2. You can directly inject session and request in ordinary classes

@Autowired
private HttpSession session;
 
@Autowired
private HttpServletRequest request;
Copy after login

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();
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template