含义
当servlet容器(Tomcat)启动时,会为每个Web应用创建一个唯一的ServletContext对象代表当前的web应用,不管在哪个servlet里面,获取到的这个类的对象都是同一个。
该对象不仅封装了当前web应用的所有信息,而且其作用范围是整个项目,实现了多个Servlet之间的数据共享,但不能跨项目获取。
服务器启动的时候,Tomcat会为托管的每一个web应用程序,创建一个ServletContext对象。当wen项目从服务器中移除、或者服务器关闭时,对象就会被销毁。
主要作用:
- 获取web应用程序的初始化参数;
- 实现多个Servlet对象的数据共享;
- 读取web应用下的资源文件。
获取
1、在HttpServlet中获取
在init方法中,可以通过ServletConfig获取
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext servletContext = config.getServletContext();
}
还可以通过request获取
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();
}
在HttpServlet
的父类GenericServlet
中也已经实现了getServletConfig()
方法和getServletContext()
方法,可以直接在Servlet中调用。
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
// 通过config对象获取
ServletConfig servletConfig = this.getServletConfig();
ServletContext servletContext1 = servletConfig.getServletContext();
// 直接获取
ServletContext servletContext2 = this.getServletContext();
}
实际上,GenericServlet
的源码中,getServletContext()
方法也是通过config对象实现的。
// GenericServlet部分源代码
public ServletContext getServletContext() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletContext();
}
2、在TomcatListener中获取
@Override
public void contextDestroyed(ServletContextEvent arg0) {
ServletContext servletContext = arg0.getServletContext();
}
3、在各种Config对象中获取
上面已经介绍了HttpServlet
的init方法的ServletConfig
对象获取,这里再介绍一下通过Filter
的FilterConfig
对象获取
@Override
public void init(FilterConfig config) throws ServletException {
ServletContext servletContext = config.getServletContext();
}
应用
获取初始化参数
与web.xml的<web-app>
标签中定义如下内容:
<context-param>
<param-name>name</param-name>
<param-value>张三</param-value>
</context-param>
与Servlet中定义如下内容:
package controller;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ServletContextTest")
public class ServletContextTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取servletContext对象
ServletContext context = this.getServletContext();
//获取参数对应的值
String name = context.getInitParameter("name");
System.out.println("Test01获取name=" + name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
控制台输出结果(成功获取):
实现资源共享
类似于request和session对象,ServletContext对象也是通过public void setAttribute(String name, Object object)
、public Object getAttribute(String name)
和public void removeAttribute(String name)
来实现数据资源共享并且操作数据的。且数据的作用域为整个web应用。
读取资源文件
参考了ServletContext的作用与应用(获取网站登陆成功总人数)
config.properties文件设置如下:
name=webapp.file.config.properties
存放位置:
Servlet代码(三种获取方式):
// 使用context.getRealPath()
private void test01() throws FileNotFoundException, IOException {
//创建servletContext对象
ServletContext context = getServletContext();
//String path = context.getRealPath("");//获取项目发布到服务器上的根路径
String path = context.getRealPath("file\\config.properties");
System.out.println("Test01 path = " + path);
//创建properties对象
Properties properties = new Properties();
//创建输入流对象
InputStream in = new FileInputStream(path);
//加载输入流
properties.load(in);
//根据key获取value值
String value = properties.getProperty("name");
System.out.println("Test01 name = " + value);
}
// 使用context.getResourceAsStream()
private void test02() throws FileNotFoundException, IOException {
ServletContext context = getServletContext();
InputStream in = context.getResourceAsStream("file/config.properties");
Properties pro = new Properties();
pro.load(in);
String name = pro.getProperty("name");
System.out.println("Test02 name = " + name);
}
// 使用this.getClass().getClassLoader().getResourceAsStream()
private void test03() throws FileNotFoundException, IOException {
Properties pro = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
pro.load(in);
String value = pro.getProperty("name");
System.out.println("Test03 name = " + value);
}
控制台输出结果:
Test01方法获取了一个服务器上资源的绝对路径