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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM