Java中的ServletContext对象

ServletContext对象:

      ServletContext类似字节码文件对象,在web创建的时候就自动生成了,并且是唯一的,跟随着项目和服务器共存亡了。通过这个对象,我们可以向里面存数据(键值对),也可以通过别的Servlet来获取这个数据;也可以根据相对(服务器)路径继来获取绝对路径。

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

ServletContext对象的生命周期?

创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状态))

销毁:web应用被卸载(服务器关闭,移除该web应用)

获得ServletContext对象:

第一种:Servlet的init方法中获得ServletConfig     初始化方法

ServletContext servletContext = config.getServletContext ();

第二种:

ServletContext servletContext = config.getServletContext ();

ServletContext的作用:

获得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);
    }

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

存储数据的区域就是域对象;

ServletContext域对象的作用范围:整个web应用(所有的web资源都可以随意向     servletcontext域中存取数据,数据可以共享)

域对象的通用的方法:

setAtrribute(String name,Object obj);       k是字符串  value是obj类型

getAttribute(String name);            强转

removeAttribute(String name);

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);
    }
}

 

posted on 2020-05-19 15:01  嘿抬头i  阅读(203)  评论(0编辑  收藏  举报