ServletContext 類

1.什麼是 ServletContext?

1ServletContext 是一個接口,它表示 Servlet 上下文對象

2、一個 web 工程,只有一個 ServletContext 對象實例。

3ServletContext 對象是一個域對象。

4ServletContext 是在 web 工程部署啓動的時候創建。在 web 工程停止的時候銷燬。

什麼是域對象?

       域對象,是可以像 Map 一樣存取數據的對象,叫域對象。

       這裏的域指的是存取數據的操作範圍,整個 web 工程。

 

  存數據 取數據 刪除數據
Map對象 put() get() remove()
域對象 setAttribute() getAttrbute() removeAttribute()

 

 

2.ServletContext 類的四個作用

1、獲取 web.xml 中配置的上下文參數 context-param

2、獲取當前的工程路徑,格式: /工程路徑

3、獲取工程部署後在服務器硬盤上的絕對路徑

代碼示例:

web.xml 中的配置:

<!--context-param 是上下文參數(它屬於整個 web 工程)-->
    <context-param>
        <param-name>username</param-name>
        <param-value>context</param-value>
    </context-param>
    <!--context-param 是上下文參數(它屬於整個 web 工程)-->
    <context-param>
        <param-name>password</param-name>
        <param-value>root</param-value>
    </context-param>

演示代碼:

 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 1、獲取 web.xml 中配置的上下文參數 context-param
        ServletContext context = getServletConfig().getServletContext();
        String username = context.getInitParameter("username");
        System.out.println("context-param 參數 username 的值是:" + username);
        System.out.println("context-param 參數 password 的值是:" +
                context.getInitParameter("password"));
        // 2、獲取當前的工程路徑,格式: /工程路徑
        System.out.println("當前工程路徑:" + context.getContextPath());
        // 3、獲取工程部署後在服務器硬盤上的絕對路徑
        /**
         * / 斜槓被服務器解析地址爲:http://ip:port/工程名/ 映射到 IDEA 代碼的 web 目錄<br/>
         */
        System.out.println("工程部署的路徑是:" + context.getRealPath("/"));
        System.out.println("工程下 css 目錄的絕對路徑是:" + context.getRealPath("/css"));
        System.out.println("工程下 imgs 目錄 1.jpg 的絕對路徑是:" + context.getRealPath("/imgs/1.jpg"));

    }

結果截圖:

 

4、像 Map 一樣存取數據

代碼示例:

ContextServlet1演示代碼:

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 獲取 ServletContext 對象
        ServletContext context = getServletContext();
        System.out.println(context);
        System.out.println("保存之前: Context1 獲取 key1 的值是:"+ context.getAttribute("key1"));
        context.setAttribute("key1", "value1");
        System.out.println("Context1 中獲取域數據 key1 的值是:"+ context.getAttribute("key1"));
    }

ContextServlet2演示代碼:

 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        System.out.println(context);
        System.out.println("Context2 中獲取域數據 key1 的值是:" + context.getAttribute("key1"));
    }

結果截圖:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章