本文最后更新于:December 3, 2021 pm
                
              
            
            
              ServletContext官方叫servlet上下文。服务器会为每一个工程创建一个对象,这个对象就是ServletContext对象。这个对象全局唯一,而且工程内部的所有servlet都共享这个对象。所以叫全局应用程序共享对象。当Web服务器启动时,会为每一个web应用程序创建一块共享的存储区域(ServletContext)。ServletContext在web服务器启动时创建,服务器关闭时销毁。
目录
1.获取ServletContext对象
- GenericServlet提供了getServletContext()方法。(this.getServletContext())
- HttpServletRequest提供了 getServletContext()方法。(request.getServletContext())
- HttpSession提供了getServletContext()方法。(session.getServletContext())
使用示例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 
 | package com.tothefor.Controller;
 import javax.servlet.ServletConfig;
 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 javax.servlet.http.HttpSession;
 import java.io.IOException;
 
 
 
 
 
 @WebServlet(value = "/sc")
 public class servletcontest extends HttpServlet {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 
 ServletContext servletContext1 = this.getServletContext();
 
 ServletContext servletContext2 = req.getServletContext();
 
 HttpSession httpSession = req.getSession();
 ServletContext servletContext3 = httpSession.getServletContext();
 
 System.out.println(servletContext1);
 System.out.println(servletContext2);
 System.out.println(servletContext3);
 }
 
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 doGet(req,resp);
 }
 }
 
 
 
 org.apache.catalina.core.ApplicationContextFacade@47320d85
 org.apache.catalina.core.ApplicationContextFacade@47320d85
 org.apache.catalina.core.ApplicationContextFacade@47320d85
 
 | 
可以发现,最后获取到的都是同一个,所以使用哪一种方法都是可以的。但推荐使用前两种。
2.ServletContext作用
2.1 获取项目真实路径
获取当前项目在服务器发布的真实路径。
String realpath = servletContext.getRealPath(“/“); 表示获取当前项目。
|  | System.out.println(servletContext1.getRealPath("/"));
 | 
2.2 获取项目上下文路径
获取当前项目上下文路径。(项目名称)
- servletContext.getContextPath();
- request.getContextPath();
|  | System.out.println(servletContext1.getContextPath());System.out.println(req.getContextPath());
 
 | 
2.3 全局容器
ServletContext拥有作用域,可以存储数据到全局容器中。
- 存储数据:servletContext.setAttribute(“key”,”value”)
- 获取数据:servletContext.getAttribute(“key”)
- 移除数据:servletContext.remove(“key”)
示例:
|  | servletContext1.setAttribute("username","loooong");String s = (String) servletContext1.getAttribute("username");
 System.out.println(s);
 
 | 
需要注意的是,ServletContext是全局域的,在任意一个里面都可以进行获取。这里为方便而只是在同一个里面进行获取。
2.4 特点
- 唯一性:一个应用对应一个ServletContext。
- 生命周期:只要容器不关闭或者应用不卸载,ServletContext就一直存在。