1.ServletContext的生命周期,随软件发行或上线而存在,随软件卸载或停用而消失。
2.ServletContext主要应用于拿到路径,或拿到加载参数
1 拿到web.xml中配置的driver路径
ServletContext servletContext = this.getServletContext(); String driver = servletContext.getInitParameter("driver"); System.out.println(driver);
2.拿到webContent下的a.txt String aPath = servletContext.getRealPath("/a.txt"); System.out.println(aPath);
3拿到web-inf下的b.txt的路径 String bPath = servletContext.getRealPath("/WEB-INF/b.txt"); System.out.println(bPath);
4.拿到src下的c.txt路径 String cPath = servletContext.getRealPath("/WEB-INF/classes/c.txt"); System.out.println(cPath);
//在读取src(classes)下的资源是可以同类加载器 ----专门加载classes 下的文件的 //getResource("")也是一个相对地址,相对于classes的 String path = ContextServlet.class.getClassLoader().getResource("c.txt").getPath(); System.out.println(path);
3.同时也可在servletContext中存储公共变量