ServletContext接口
1.基本概念
javax.servlet.ServletContext接口主要用于定义一组方法,Servlet使用这些方法与它的Servlet容 器通信。
服务器容器在启动时会为每个项目创建唯一的一个ServletContext对象,用于实现多个Servlet之间 的信息共享和通信。
在Servlet中通过this.getServletContext()方法可以获得ServletContext对象。
2.配置方式
<!--在web.xml中配置ServletContext初始化参数 -->
<context-param>
<param-name>username</param-name>
<param-value>scott</param-value>
<context-param>
<context-param>
<param-name>password</param-name>
<param-value>tiger</param-value>
<context-param>
3.常用的方法
方法声明 | 功能介绍 |
String getInitParameter(String name) | 返回包含初始化参数值的字符串,如果该参数不存在,则返回 null |
Enumeration getInitParameterNames() | 将servlet的初始化参数的名称作为字符串对象的枚举返回,如果servlet没有初始化参数,则返回空枚举 |
String getRealPath(String path) | 返回包含给定虚拟路径的实际路径的字符串 |
String getContextPath() | 返回与此上下文关联的主路径 |
InputStream getResourceAsStream(String path) | 将位于指定路径的资源作为InputStream对象返回 |
void setAttribute(String name, Object object) | 将指定的属性名和属性值绑定到当前对象 |
Object getAttribute(String name) | 根据执行的属性名获取属性值 |
void removeAttribute(String name) | 删除指定的属性名信息 |
示例:
package com.lagou.demo02;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
public class ContextServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.配置参数的获取
ServletContext servletContext = getServletConfig().getServletContext();
Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String s = initParameterNames.nextElement();
System.out.println( s + "对应的值为:" + servletContext.getInitParameter(s));
}
System.out.println("----------------------------------------------------------");
// 2.相关路径的获取
// 本质上就是获取工程路径 /工程名
String contextPath = servletContext.getContextPath();
System.out.println("获取上下文关联的路径信息为:" + contextPath); // /task01_demo02
// / 在服务器被解析为: http://ip地址:端口号/工程名 获取实际路径信息
// 获取到的是部署工程路径信息 对应 当前工程中的web目录
String realPath = servletContext.getRealPath("/");
// C:\Users\Marz\IdeaProjects\javaweb\out\artifacts\task01_demo02_war_exploded\
System.out.println("获取到的实际路径信息为:" + realPath);
System.out.println("----------------------------------------------------------");
// 3.设置和获取属性信息
servletContext.setAttribute("key", "value");
Object key = servletContext.getAttribute("key");
System.out.println("根据参数指定的属性名获取到的属性值为:" + key); // value
servletContext.removeAttribute("key");
key = servletContext.getAttribute("key");
System.out.println("根据参数指定的属性名获取到的属性值为:" + key); // null
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}