1. ServletContext 是什么
2. 利用ServletContext 读取web.xml全局变量
3. 利用ServletContext 建立全局属性(不存在于web.xml)
4. 利用ServletContext 获取工程目录下的文件绝对路径
5. 利用ServletContext 读取properties配置文件中的值
(一)ServletContext 是什么
1. WEB容器在启动时,它会为每个WEB应用创建一个ServletContext 对象,它代表当前WEB应用。
2. 一个WEB应用的所有Servlet共享同一个 ServetContext 对象。
3.应用:
(1)获取WEB应用的全局初始化参数。
(2)利用ServletContext 读取资源文件
(二)利用ServletContext 读取web.xml 全局变量
<context-param>用于在web.xml中设置全局变量,如:
<context-param>
<param-name>context_key</param-name>
<param-value>context_value</param-value>
</context-param>
在java代码中通过ServletContext对象获取web.xml中的全局变量:
1. 若在 init(ServletConfig config)方法中,ServletContext对象可以通过 ServletConfig 提供的方法获取
2. 通过ServletContext 的getInitParam()方法获取变量的值,以String的形式返回
public class HttpServlet_demo extends HttpServlet { //HttpServlet
//HttpServlet 中 的init(ServletConfig config)方法
public void init(ServletConfig config) throws ServletException {
super.init(config);
//获取ServletContext对象
ServletContext sc = config.getServletContext();
String param = sc.getInitParameter("context_key"); //context_key为web.xml的全局变量的名字,返回的是变量的值
System.out.println(param);
}
}
(三)利用ServletContext 建立全局属性(不存在于web.xml)
1.此属性可以被一个项目里的全部servlet共享
2.用到 ServletContext的 getAttribute(name)方法。 参数name表示属性的名字。此方法用于返回给定名字的属性的值,若此名字不存在,则返回null。返回的是Object对象
3. setAttributte(name,n) 用于对全局属性赋值,name表示要赋值的属性,n表示要赋的值
public class HttpServlet_demo extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
/*通过this获取ServletContext对象*/
ServletContext sc = this.getServletContext();
/*创建count对象,名为count*/
Integer count = (Integer)sc.getAttribute("count");
if(count == null){
/*给全局属性count赋初始值为1*/
sc.setAttribute("count", 1);
count = (Integer) sc.getAttribute("count");
}
else
/*给全局属性count赋值,+1*/
sc.setAttribute("count", ++count);
System.out.println(count);
String result = "count"+count;
}
}
(四)利用ServletContext 获取工程目录下的文件绝对路径
利用 ServletContext 对象的 getRealPath()方法,String path = sc.getRealPath("/") 返回的是工程的绝对路径
若要获得test2.properties的路径,则:String path = sc.getRealPath("test2.properties");
注意:部署后的项目是在 WEB-INF 下的,所以String path = sc.getRealPath("/"); 获得的路径也就是WEB-INF所在的绝对路径
public class HttpServlet_demo extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
ServletContext sc = config.getServletContext();
String path = sc.getRealPath("test2.properties");
System.out.println("绝对路径:"+path);
}
}
(五)利用ServletContext 读取properties配置文件中的值
/*获取ServletContext对象*/
ServletContext sc = this.getServletContext();
/*获取test2的输入流*/
InputStream in = sc.getResourceAsStream("/WEB-INF/test2.properties");
/*创建配置文件类*/
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.get("name")); //获取配置文件test2.properties中的name的值