1.ServletContext 类简介
- 1、ServletContext 是一个接口,它表示 Servlet 上下文对象
- 2、一个 web 工程,只有一个 ServletContext 对象实例。
- 3、ServletContext 对象是一个域对象。
- 4、ServletContext 是在 web 工程部署启动的时候创建。在 web 工程停止的时候销毁。
注:
域对象,是可以像 Map 一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个 web 工程。
2.ServletContext 类的四个作用
- 1、获取 web.xml 中配置的上下文参数 context-param
- 2、获取当前的工程路径,格式: /工程路径
- 3、获取工程部署后在服务器硬盘上的绝对路径
- 4、像 Map 一样存取数据
2.1 获取XML配置的上下文参数、文件工程路径、绝对路径
例如Servlet在XML中的配置为:
<!--context-param 是上下文参数(它属于整个 web 工程)-->
<context-param>
<param-name>username</param-name>
<param-value>abc</param-value>
</context-param>
Servlet 中的代码:
public class HelloServlet03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletConfig().getServletContext();
// 1、获取 web.xml 中配置的上下文参数 context-param
String username = context.getInitParameter("username");
System.out.println("context-param 参数 username 的值是:" + username);
// 2、获取当前的工程路径,格式: /工程路径
System.out.println( "当前工程路径:" + context.getContextPath() );
// 3、获取工程部署后在服务器硬盘上的绝对路径
System.out.println("工程部署的路径是:" + context.getRealPath("/"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
2.2 像 Map 一样存取数据
Servlet 中的代码:
public class HelloServlet03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletConfig().getServletContext();
// 1、获取 web.xml 中配置的上下文参数 context-param
String username = context.getInitParameter("username");
System.out.println("更改前的username:" + username);
//2、设置 web.xml 中配置的上下文参数 context-param
context.setAttribute("username", "edf");
System.out.println("更改后的username:" + context.getAttribute("username"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
实验结果: