一、什么是ServletContext
- ServletContext是一个接口, 它表示Servlet上下文对象
- 一个web工程,只有一个ServletContext对象实例。
- ServletContext 对象是一个域对象。
- ServletContext 是在web工程部署启动的时候创建。在web工程停止的时候销毁。
二、什么是域对象?
域对象,是可以像Map一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个web工程。
存数据 取数据 删除数据
Map put() get() remove()
域对象 setAttribute() getAttribute() removeAttribute();
所有Servlet程序都可以在ServletContext中存取数据,都可以操作ServletContext,因为一个web工程中只有一个ServletContext对象
package com.ftn.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class ContextServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、获取web.xml中配置的上下文参数context param
ServletContext context = getServletConfig().getServletContext();
String username = context.getInitParameter("username");
String password = context.getInitParameter("password");
System.out.println("context-param参数username的值是" + username);
System.out.println("context-param参数password的值是" + password);
// 2、获取当前的工程路径,格式: /工程路径
System.out.println("当前工程路径:" + context.getContextPath());
// 3、获取工程部署后在服务器硬盘上的绝对路径
//斜杠被服务器解析地址为:http://ip:port/工程名/
System.out.println("工程部署的路径:" + context.getRealPath("/"));
// 4、像Map一样存取数据
System.out.println(context.getAttribute("key1"));
//存数据
context.setAttribute("key1","value1");
//取数据
System.out.println(context.getAttribute("key1"));
//打印地址
System.out.println(context);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
11
context-param标签中的内容属于整个web工程,所有Servlet程序都可以使用
username
root
password
123456



