1、介绍
Servlet引擎为每个WEB应用程序都创建一个对应的ServletContext对象,ServletContext对象被包含在ServletConfig对象中,调用ServletConfig.getServletContext方法可以返回ServletContext对象的引用。
由于一个WEB应用程序中的所有Servlet都共享同一个ServletContext对象,所以,ServletContext对象被称之为 application 对象(Web应用程序对象)。
功能:
①获取WEB应用程序的初始化参数
②记录日志
③application域范围的属性
④访问资源文件
⑤获取虚拟路径所映射的本地路径
⑥WEB应用程序之间的访问
⑦ServletContext的其他方法
该对象代表当前 WEB 应用: 可以认为 SerlvetContext 是当前 WEB 应用的一个大管家. 可以从中获取到当前 WEB 应用的各个方面的信息.
2、可以由 SerlvetConfig 获取
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
// 获取 ServletContext 对象
ServletContext servletContext = arg0.getServletContext();
}
3、获取当前 WEB 应用的初始化参数
设置初始化参数: 可以为所有的 Servlet 所获取,而 Servlet 的初始化参数只用那个 Serlvet 可以获取。
<!-- 配置当前 WEB 应用的初始化参数 -->
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
方法:
getInitParameter
getInitParameterNames
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
// 获取 ServletContext 对象
ServletContext servletContext = arg0.getServletContext();
String driver = servletContext.getInitParameter("driver");
System.out.println("dirver:" + driver);
Enumeration<String> names2 = servletContext.getInitParameterNames();
while (names2.hasMoreElements()) {
String name = names2.nextElement();
System.out.println("-->" + name);
}
}
为WEB应用程序设置初始化参数的好处在于不需要修改Servlet源程序,就可以改变一些参数信息。
4、获取当前 WEB 应用的某一个文件在服务器上的绝对路径, 而不是部署前的路径
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
// 获取 ServletContext 对象
ServletContext servletContext = arg0.getServletContext();
String realPath = servletContext.getRealPath("/WEB-INF/web.xml");
System.out.println(realPath);
}
5、获取当前 WEB 应用的名称
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
// 获取 ServletContext 对象
ServletContext servletContext = arg0.getServletContext();
String contextPath = servletContext.getContextPath();
System.out.println(contextPath);
}
6、获取当前 WEB 应用的某一个文件对应的输入流
getResourceAsStream(String path): path 的 / 为当前 WEB 应用的根目录.
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
// 获取 ServletContext 对象
ServletContext servletContext = arg0.getServletContext();
try {
Properties pros = new Properties();
InputStream is = servletContext.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
System.out.println(is);
pros.load(is);
System.out.println(pros.getProperty("name"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}