JAVA基础之ServletContext对象

个人理解:

   ServletContext类似字节码文件对象,在web创建的时候就自动生成了,并且是唯一的,跟随着项目和服务器共存亡了。通过这个对象,我们可以向里面存数据(键值对),也可以通过别的Servlet来获取这个数据;也可以根据相对(服务器)路径继来获取绝对路径。根据这个信息我们可以在以后创建文件的过程中,将静态资源的文件尽量创建在web-content文件夹下,而项目文件、配置文件创建在src下。不要直接创建在web文件夹下(不会在服务器上生成)。

一、ServletContext对象:

  ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象内部封装是该web应用的信息,ServletContext对象一个web应用只有一个。

二、ServletContext对象的生命周期:

创建:该web应用被加载且服务器开启时创建;

销毁:web应用被卸载(移除该项目应用)或者服务器关闭。

三、获得ServletContext对象:

1、Servlet的init方法中获得ServletConfig 

ServletContext servletContext = config.getServletContext ()

2、

ServletContext  servletContext = this.getservletContext ()

四、ServletContext的作用:

1、获得web应用全局的初始化参数;

2、获得web应用中任何资源的绝对路径:

(通过服务器的相对路径,得到一个在服务器上的绝对路径)

String path = context.getRealPath(相对于该web应用的相对地址);
public class Servlet01 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext context =getServletContext();
        //获取相对于服务器的相对路径获取绝对路径
        String patha=context.getRealPath("WEB-INF/classes/a.txt");
        String pathb=context.getRealPath("b.txt");
        String pathc=context.getRealPath("WEB-INF/c.txt");
        //d.txt创建在WEB04文件下,不会在服务器上找到的。以后静态资源创建在WebContent下,项目文件、配置文件在src下
        System.out.println(patha);
        System.out.println(pathb);
        System.out.println(pathc);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

3、ServletContext是一个域对象(存储数据的区域):

ServletContext域对象的作用范围:整个web

(所有的web资源都可以随意向 ServletContext 域中存取数据,数据可以分享)。

域对象的通用方法:

setAtrribute(String name,Object obj);
getAttribute(String name);
removeAttribute(String name);
public class Servlet02 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext context=getServletContext();    
        //往ServletContext域中设置值
        context.setAttribute("name", "zs");        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
public class Serlvlet03 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext context=getServletContext();
        //获取ServletContext域中的值
        String name=(String)context.getAttribute("name");
        response.getWriter().write(name);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
原文地址:https://www.cnblogs.com/21-forever/p/11115396.html