Spring如何获取ServletContext

一、获取ServletContext的几种方式

实现WebApplicationInitializer接口,重写onStartup方法
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;

public class ApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println(servletContext);
    }
}
使用ServletContextListener

创建一个实现ServletContextListener的监听器

// 必不可少,声明为监听器,注册到web容器中
@WebListener
public class InitContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        System.out.println(servletContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
使用ContextLoader
WebApplicationContext webApplicationContext  = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
使用spring自动注入
@Autowired
private ServletContext servletContext;
request获取servletContext
ServletContext servletContext = request.getServletContext();

二、使用ServletContext存取

添加属性:setAttribute(String name,Object ob);

得到值:   getAttribute(String);    //返回Object

删除属性:removeAttribute(String name);

posted @ 2020-05-17 14:50  codedot  阅读(886)  评论(0编辑  收藏  举报