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);
时刻与技术进步,每天一点滴,日久一大步!!!
本博客只为记录,用于学习,如有冒犯,请私信于我。