ServletContext类的理解
什么是ServletContext类?
- ServletContext是Servlet中的上下文对象
- 一个web工程中只有一个ServletContext对象实例
- ServletContext对象是一个域对象
- ServletContext对象在程序部署时创建,在程序停止时消亡
什么是域对象?
域对象就是像Map一样,以键值对的方式呈现数据, 有存储、获取、删除数据的方式
两种存储类型的存储方法:
类 | 存储 | 获取 | 删除 |
---|---|---|---|
Map | put() | get() | remove() |
域对象 | setAttribute() | getAttribute() | removeAttribute() |
一般我们看到有xxxAttribute()方法都是域对象
ServletContext的4大作用:
- 获取web.xml中配置的上下文参数context-param
- 获取当前工程的路径 格式: /工程路径
- 获取Idae中当前工程在硬盘中的真实路径
- 能像Map一样存储、获取属性值
public class ContextServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletContext的四大作用:
//1. 获取web.xml配置信息中的context-param参数
String username = getServletContext().getInitParameter("username");
System.out.println("获取的username的值: "+username);
String name = getServletContext().getInitParameter("name");
System.out.println("获取的name的值: "+name);
//2.获取Servlet程序的工程路径, 格式: /工程路径
String contextPath = getServletContext().getContextPath();
System.out.println("setvlet的工程路径: "+contextPath); //servlet的工程路径: /06_Servlet
//3.获取在Idea中当前工程在硬盘的真实路径
// '/'被服务器解析地址为: http://ip:port/工程路径 映射到IDEA代码的web目录
String realPath = getServletContext().getRealPath("/");
System.out.println("工程的真实路径: " + realPath); //工程的真实路径: D:\Java-project\06_Servlet\target\servlet-1.0-SNAPSHOT\
//4.能像Map一样存储、获取属性值
getServletContext().setAttribute("key","value1");
//获取key的属性值
System.out.println(getServletContext().getAttribute("key"));
}
}
web.xml下的context-param配置信息
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--context-param标签,给ServletContext获取的元素, 它在整个工程中是共享的,
相当于static修饰符-->
<context-param>
<param-name>username</param-name>
<param-value>userabc</param-value>
</context-param>
<context-param>
<param-name>name</param-name>
<param-value>root</param-value>
</context-param>
<servlet>
<servlet-name>ContextServlet</servlet-name>
<servlet-class>com.example.servlet.ContextServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
注意点: 在Servlet程序部署后, 使用ServletContext存储数据的代码 属性名A=属性值B , 在这段代码前面如果有调用A属性的方法,当我们第一次调用这个程序的页面时,在控制台会显示它的值为null,我再次刷新页面后,它会更新属性值为B,此时它的属性值就存储为B.
如果有其他程序为这个属性名的值重新赋值, 那就会替换原有的值
而当程序停止后,再次部署程序,那么这需要重新做一边赋值操作