目录
1 ServletContext概述
服务器会为每个应用创建一个ServletContext对象:
-
ServletContext对象的创建是在服务器启动时完成的;
-
ServletContext对象的销毁是在服务器关闭时完成的。
ServletContext对象的作用是在整个Web应用的动态资源之间共享数据!例如在AServlet中向ServletContext对象中保存一个值,然后在BServlet中就可以获取这个值,这就是共享数据了。
2.获取ServletContext
在Servlet中获取ServletContext对象:
-
在void init(ServletConfig config)中:ServletContext context = config.getServletContext();,ServletConfig类的getServletContext()方法可以用来获取ServletContext对象;
public class MyServlet implements Servlet { public void init(ServletConfig config) { ServletContext context = config.getServletContext(); } //… }
在GenericeServlet或HttpServlet中获取ServletContext对象:
GenericServlet类有getServletContext()方法,所以可以直接使用this.getServletContext()来获取;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
{
ServletContext context = this.getServletContext();
}
}