Servlet中的getServletContext()方法詳解


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上下文中刪除指定屬性。
 
 
---------------------
作者:rnzhiw
來源:CSDN
原文:https://blog.csdn.net/rnzhiw/article/details/83349325
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

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



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