什么是ServletContext对象?
ServletContext代表的是一个web应用的环境(上下文)对象,ServletContext对象内部封装的是该web应用的信息。
一个web应用只有一个ServletContext对象。\color{red}{一个web应用只有一个ServletContext对象。}一个web应用只有一个ServletContext对象。
Servlet的生命周期
- 创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状态))
- 销毁:web应用被卸载(服务器关闭,移除该web应用)
获得ServletContext对象
第一种:
ServletContext servletContext = config.getServletContext();
第二种(常用):
ServletContext servletContext1 = this.getServletContext();
ServletContext的作用
- 获得web应用全局的初始化参数:
web.xml中配置初始化参数
<!-- 配置初始化参数 -->
<context-param>
<param-name>testStr</param-name>
<param-value>helloWorld</param-value>
</context-param>
通过ServletContext获得初始化参数:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//获得初始化参数
String testStr = servletContext.getInitParameter("testStr");
System.out.println(testStr);
}
通过浏览器访问,控制台输出:
helloWorld
- 获得web应用中任何资源的绝对路径(重要):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//获的资源相对于该web的相对路径
String realPath = servletContext.getRealPath("index.jsp");
System.out.println(realPath);
}
通过浏览器访问,控制台输出:
F:\IDEAworkspace\JavaEEDemo\out\artifacts\JavaEEDemo_war_exploded\index.jsp
ServletContext是一个域对象
域对象:
域对象是服务器在内存上创建的存储空间,用于在不同动态资源(servlet)之间传递与共享数据。
域对象通用方法:
| 方法 | 描述 |
|---|---|
| setAttribute(String name,Object value); | 向域对象中添加数据,添加时以key-value形式添加 |
| getAttribute(String name); | 根据指定的key读取域对象中的数据 |
| removeAttribure(String name); | 根据指定的key从域对象中删除数据 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//向域对象中存入数据
servletContext.setAttribute("str", "helloWorld");
//从域对象中取出数据
String str = (String) servletContext.getAttribute("str");
//从域对象中删除数据
servletContext.removeAttribute("str");
}
ServletContext存储数据的特点:
全局共享,里面的数据所有动态资源都可以写入和读取。
ServletContext获取当前工程名字
核心方法:
getServletContext().getContextPath();
示例:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得工程名字
String contextPath = getServletContext().getContextPath();
System.out.println(contextPath);
}
通过浏览器访问,控制台输出:
/JavaEEDemo
本文详细介绍了ServletContext对象的概念,其作为web应用的环境对象,负责封装整个web应用的信息。文章讲解了ServletContext的生命周期,如何获取该对象,以及它在获取初始化参数、资源路径、存储数据和获取工程名字等方面的作用。
9659

被折叠的 条评论
为什么被折叠?



