spring-web6.0.8版本的ServletContext怎么获取
时间: 2024-05-10 08:16:44 浏览: 116
在Spring中获取ServletContext有以下几种方式:
1. 在Controller中使用 @Autowired 注解注入ServletContext对象:
```java
@Autowired
private ServletContext servletContext;
```
2. 在HttpSessionListener中获取ServletContext对象:
```java
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
// do something with servletContext
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// do something
}
}
```
3. 在任何一个Spring管理的Bean中,实现ServletContextAware接口:
```java
@Service
public class MyService implements ServletContextAware {
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public void doSomething() {
// do something with servletContext
}
}
```
阅读全文