ServletContext (上下文对象)

一、什么是ServletContext

  • ServletContext代表是一个web应用的上下文对象(web应用对象)
  • 里面封装的都是web应用信息
  • 一个ServletContext对应一个应用

二、ServletContext的生命周期

  • 在服务器一启动的时候就会创建
  • 在服务器关闭的时候销毁

三、如何获得上下文

  • 通过init方法当中一个参数ServletConfig来获取
public void init(ServletConfig config) throws ServletException {
    System.out.println(config);
    ServletContext context = config.getServletContext();
    System.out.println(context);
}

/** 运行结果
  * org.apache.catalina.core.StandardWrapperFacade@3e478880
  * org.apache.catalina.core.ApplicationContextFacade@24391b1e
  */
  • 直接在HttpServlet当中获取
    • this.getServletContext
    • 这种方法本质还是通过config来去获取的

四、获取全局的初始化参数

初始化参数不能再某一个Servlet当中来去配置。在最外层来去配置

获取全局初始化参数

五、获得Web应用中某一个资源的绝对路径

各文件的结构

获取 WebContent 下的文件

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String realPatha = context.getRealPath("a.txt");
    System.out.println(realPatha);
    String realPathb = context.getRealPath("WEB-INF/b.txt");
    System.out.println(realPathb);
}

获取 Java Resources 下的文件

  • 方法一:和获取 WebContent 下的文件一样,先获取根目录,然后拼接。
  • 方法二:通过类加载器获取字节码目录
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext context = this.getServletContext();

    String pathc = one.class.getClassLoader().getResource("c.txt").getPath();
    System.out.println(pathc);
    // 解决路径中 空格显示为 %20
    pathc = URLDecoder.decode(pathc, "utf-8");
    System.out.println(pathc);

    String pathd = one.class.getClassLoader().getResource("com/xzh/servlet/d.txt").getPath();
    pathd = URLDecoder.decode(pathd, "utf-8");
    System.out.println(pathd);

    String pathe = one.class.getClassLoader().getResource("e.txt").getPath();
    pathe = URLDecoder.decode(pathe, "utf-8");
    System.out.println(pathe);
}

六、ServletContext是一个域对象

  • 域 :能够存储数据。
  • 域对象 :能够存取数据数据就的对象。

ServletContext域对象的作用范围:

  • 整个web应用,所有的web资源都可以进行存取数据
  • 数据是可以共享的

获取完ServletContext之后向里面写数据

context.setAttribute(String name,Object value);

获取完ServletContext之后,通过name取出存放的数据

context.getAttribute(String name);

获取完ServletContext之后,删除指定名称的值

Context.removeAttribute(String name);

只要是一个域对象上,基本上里面都有这几个方法

posted @ 2019-04-01 20:54  Lomen~  阅读(2440)  评论(0编辑  收藏  举报