1. 程式人生 > >Servlet中的getServletContext()方法詳解

Servlet中的getServletContext()方法詳解

     這兩天剛剛學到這個類,看了視訊,翻了書,我覺得還是比較亂,javaee裡面的jdk也寫的比較亂,所以今天有時間整理一下吧:

其實我覺得還是從下面這段話先來解釋吧:

public class ServletContext01 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.獲取物件
        ServletContext context = getServletContext();


        String address = context.getInitParameter("address");
        System.out.println(address);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

web.xml引數設定:

 <context-param>
    <param-name>address</param-name>
    <param-value>中國深圳</param-value>
  </context-param>

這個是一個比較經典的doGet和doPost方法的案例,繼承了httpservlet類,

我覺得可能剛接觸的人應該是 ServletContext context = getServletContext();這句話不是很懂,其實我們可以這麼理解,一個servlet可以使用getservletcontext()方法得到了web應用中的servletcontext,從而使用servletcontext介面的一些方法:比如我們可以看到後面的那句話

String address = context.getInitParameter("address");實際上就是用了servletcontext接口裡面的getInitParameter()方法:而address就是引數的名稱,獲得的值為中國深圳,所以有沒有覺得這樣很方便?

------------------------------------------------------------------------------------------------------------------------------------------------------------

剛在另一篇部落格裡面有看到他對於getservletcontext()方法的解釋,可能比較文字古板,(不想看的可以跳過這段,我覺得不忙的話看看也挺好的)

一個servlet上下文是servlet引擎提供用來服務於Web應用的介面。Servlet上下文具有名字(它屬於Web應用的名字)唯一對映到檔案系統的一個目錄。
一個servlet可以通過ServletConfig物件的getServletContext()方法得到servlet上下文的引用,如果servlet直接或間接呼叫子類GenericServlet,則可以使用getServletContext()方法。
Web應用中servlet可以使用servlet上下文得到:
1.在呼叫期間儲存和檢索屬性的功能,並與其他servlet共享這些屬性。
2.讀取Web應用中檔案內容和其他靜態資源的功能。
3.互相傳送請求的方式。
4.記錄錯誤和資訊化訊息的功能。

-------------------------------------------------------------------------------------------------------------------------------------------------------------

 

下面總結servletcontext接口裡面的方法:

1.String getInitParameter(String name)    返回指定上下文範圍的初始化引數值。

2.Object getAttribute(String name)    返回servlet上下文中具有指定名字的物件,或使用已指定名捆綁一個物件。從Web應用的標準觀點看,這樣的物件是全域性物件,因為它們可以被同一servlet在另一時刻訪問。或上下文中任意其他servlet訪問。 

這個方法我用過例子:(我在做計數網站曾經被登入過幾次用過這個方法):

下面是我的程式:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //1.獲取資料
        String userName = request.getParameter("username");        //httpservletrequest裡面的方法。獲取請求頭中的引數,
        String password = request.getParameter("password");
//        System.out.println("userName="+userName+"password="+password);
        
        //2.校驗資料
        
        PrintWriter pw = response.getWriter();    //用了這個輸出流可以直接將文字寫在瀏覽器上        
        
        
        if("admin".equals(userName) && "123".equals(password)) {
            pw.write("login success.....");
            //如果成功的話,就跳轉到login_success.html那裡
            
            //成功的次數累加:
            //保留之前存的值,然後在舊的值的基礎上+1
            Object obj = getServletContext().getAttribute("count");        //getAttribute是servlet裡面的方法
            
            
            //預設就是0次
            int totalCount = 0;
            if(obj != null) {
                totalCount = (int)obj;
            }
            
            System.out.println("已登入成功的次數是:"+totalCount);
            
            
            //給這個count賦新的值
            getServletContext().setAttribute("count", totalCount+1);
            
            
            //跳到成功的頁面
            //設定狀態碼,進行 重新定位狀態碼
            
            
            response.setStatus(302);
            
            //定位跳轉的位置是哪一個頁面
            response.setHeader("Location", "login_success.html");
            
        } else {
            pw.write("login failed.....");
        }
        
    }

3.String getRealPath(String path)    給定一個URI,返回檔案系統中URI對應的絕對路徑。如果不能進行對映,返回null。

下面是我寫過的程式程式碼:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //獲取servletcontext物件
        ServletContext context = this.getServletContext();
        //獲取給定的檔案在伺服器上面的絕對路徑
        String path = context.getRealPath("");
        
        System.out.println(path);     

 

這個實際上輸出的就是檔案在電腦中的絕對路徑,也就是讀取web中的資原始檔;

 

3.void setAttribute(String name,Object obj)    設定servlet上下文中具有指定名字的物件。 

 

下面幾個我還沒用過,我用了以後有時間再補充吧:

4.Enumeration getAttributeNames()    返回儲存在servlet上下文中所有屬性名字的列舉。       
5.ServletContext getContext(String uripath)    返回對映到另一URL的servlet上下文。在同一伺服器中URL必須是以“/”開頭的絕對路徑。 

6.Enumeration getInitParameterNames()    返回(可能為空)指定上下文範圍的初始化引數值名字的列舉值。       
7.int getMajorVersion()    返回此上下文中支援servlet API級別的最大和最小版本號。       
8.int getMinorVersion()           
9.String getMimeType(String fileName)    返回指定檔名的MIME型別。典型情況是基於副檔名,而不是檔案本身的內容(它可以不必存在)。如果MIME型別未知,可以返回null。       
10.RequestDispatcher getNameDispatcher(String name)    返回具有指定名字或路徑的servlet或JSP的RequestDispatcher。如果不能建立RequestDispatch,返回null。如果指定路徑,必須心“/”開頭,並且是相對於servlet上下文的頂部。       
11.RequestDispatcher getNameDispatcher(String path)           

13.URL getResource(String path)    返回相對於servlet上下文或讀取URL的輸入流的指定絕對路徑相對應的URL,如果資源不存在則返回null。       
14.InputStream getResourceAsStream(String path)           
15.String getServerInfo()    返順servlet引擎的名稱和版本號。       
16.void log(String message)
17.void log(String message,Throwable t)    將一個訊息寫入servlet註冊,如果給出Throwable引數,則包含棧軌跡。       
18.void removeAttribute(String name)    從servlet上下文中刪除指定屬性。