2025-06-20

JavaWeb:Servlet。

Servlet概述

生命周期方法:

void init(ServletConfig):出生之後(1次); void service(ServletRequest request, ServletResponse response):每次處理請求時都會被調用; void destroy():臨死之前(1次);

特性:

單例,一個類隻有一個對象;當然可能存在多個Servlet類! 線程不安全的,所以它的效率是高的!

這裡寫圖片描述

Servlet類由我們來寫,但對象由服務器來創建,並且由服務器來調用相應的方法。

1、什麼是Servlet

Servlet是JavaWeb的三大組件之一,它屬於動態資源。Servlet的作用是處理請求,服務器會把接收到的請求交給Servlet來處理,在Servlet中通常需要:

接收請求數據; 處理請求; 完成響應。

例如客戶端發出登錄請求,或者輸出註冊請求,這些請求都應該由Servlet來完成處理!Servlet需要我們自己來編寫,每個Servlet必須實現javax.servlet.Servlet接口。

2、實現Servlet的方式

實現Servlet有三種方式:

實現javax.servlet.Servlet接口; 繼承javax.servlet.GenericServlet類; 繼承javax.servlet.http.HttpServlet類;

通常我們會去繼承HttpServlet類來完成我們的Servlet,但學習Servlet還要從javax.servlet.Servlet接口開始學習。

Servlet.java

public interface Servlet {
    public void init(ServletConfig config) throws ServletException;
    public ServletConfig getServletConfig();
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException;
    public String getServletInfo();
    public void destroy();
}

3、創建helloservlet應用

我們開始第一個Servlet應用吧!首先在webapps目錄下創建helloservlet目錄,它就是我們的應用目錄瞭,然後在helloservlet目錄中創建準備JavaWeb應用所需內容:

創建/helloservlet/WEB-INF目錄; 創建/helloservlet/WEB-INF/classes目錄; 創建/helloservlet/WEB-INF/lib目錄; 創建/helloservlet/WEB-INF/web.xml文件;

接下來我們開始準備完成Servlet,完成Servlet需要分為兩步:

編寫Servlet類; 在web.xml文件中配置Servlet;

HelloServlet.java

public class HelloServlet implements Servlet {
    public void init(ServletConfig config) throws ServletException {}
    public ServletConfig getServletConfig() {return null;}
    public void destroy() {}
    public String getServletInfo() {return null;}

    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        System.out.println("hello servlet!");
    }
}

我們暫時忽略Servlet中其他四個方法,隻關心service()方法,因為它是用來處理請求的方法。我們在該方法內給出一條輸出語句!

web.xml(下面內容需要背下來)


        hello
        cn.itcast.servlet.HelloServlet



        hello
        /helloworld
  

在web.xml中配置Servlet的目的其實隻有一個,就是把訪問路徑與一個Servlet綁定到一起,上面配置是把訪問路徑:“/helloworld”與“cn.itcast.servlet.HelloServlet”綁定到一起。

:指定HelloServlet這個Servlet的名稱為hello; :指定/helloworld訪問路徑所以訪問的Servlet名為hello。

和通過這個元素關聯在一起瞭!

接下來,我們編譯HelloServlet,註意,編譯HelloServlet時需要導入servlet-api.jar,因為Servlet.class等類都在servlet-api.jar中。

javac -classpath F:/tomcat6/lib/servlet-api.jar -d . HelloServlet.java
然後把HelloServlet.class放到/helloworld/WEB-INF/classes/目錄下,然後啟動Tomcat,在瀏覽器中訪問:https://localhost:8080/helloservlet/helloworld即可在控制臺上看到輸出!

/helloservlet/WEB-INF/classes/cn/itcast/servlet/HelloServlet.class;

Servlet接口

1、Servlet的生命周期

所謂xxx的生命周期,就是說xxx的出生、服務,以及死亡。Servlet生命周期也是如此!與Servlet的生命周期相關的方法有:

void init(ServletConfig); void service(ServletRequest,ServletResponse); void destroy();

1.1 Servlet的出生

服務器會在Servlet第一次被訪問時創建Servlet,或者是在服務器啟動時創建Servlet。如果服務器啟動時就創建Servlet,那麼還需要在web.xml文件中配置。也就是說默認情況下,Servlet是在第一次被訪問時由服務器創建的。

而且一個Servlet類型,服務器隻創建一個實例對象,例如在我們首次訪問https://localhost:8080/helloservlet/helloworld時,服務器通過“/helloworld”找到瞭綁定的Servlet名稱為cn.itcast.servlet.HelloServlet,然後服務器查看這個類型的Servlet是否已經創建過,如果沒有創建過,那麼服務器才會通過反射來創建HelloServlet的實例。當我們再次訪問https://localhost:8080/helloservlet/helloworld時,服務器就不會再次創建HelloServlet實例瞭,而是直接使用上次創建的實例。

在Servlet被創建後,服務器會馬上調用Servlet的void init(ServletConfig)方法。請記住, Servlet出生後馬上就會調用init()方法,而且一個Servlet的一生。這個方法隻會被調用一次。這好比小孩子出生後馬上就要去剪臍帶一樣,而且剪臍帶一生隻有一次。

我們可以把一些對Servlet的初始化工作放到init方法中!

1.2 Servlet服務

當服務器每次接收到請求時,都會去調用Servlet的service()方法來處理請求。服務器接收到一次請求,就會調用service() 方法一次,所以service()方法是會被調用多次的。正因為如此,所以我們才需要把處理請求的代碼寫到service()方法中!

1.3 Servlet的離去

Servlet是不會輕易離去的,通常都是在服務器關閉時Servlet才會離去!在服務器被關閉時,服務器會去銷毀Servlet,在銷毀Servlet之前服務器會先去調用Servlet的destroy()方法,我們可以把Servlet的臨終遺言放到destroy()方法中,例如對某些資源的釋放等代碼放到destroy()方法中。

1.4 測試生命周期方法

修改HelloServlet如下,然後再去訪問https://localhost:8080/helloservlet/helloworld

public class HelloServlet implements Servlet {
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Servlet被創建瞭!");
    }
    public ServletConfig getServletConfig() {return null;}
    public void destroy() {
        System.out.println("Servlet要離去瞭!");
    }
    public String getServletInfo() {return null;}

    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        System.out.println("hello servlet!");
    }
}

在首次訪問HelloServlet時,init方法會被執行,而且也會執行service方法。再次訪問時,隻會執行service方法,不再執行init方法。在關閉Tomcat時會調用destroy方法。

2、Servlet接口相關類型

在Servlet接口中還存在三個我們不熟悉的類型:

ServletRequest:service() 方法的參數,它表示請求對象,它封裝瞭所有與請求相關的數據,它是由服務器創建的; ServletResponse:service()方法的參數,它表示響應對象,在service()方法中完成對客戶端的響應需要使用這個對象; ServletConfig:init()方法的參數,它表示Servlet配置對象,它對應Servlet的配置信息,那對應web.xml文件中的元素。

2.1 ServletRequest和ServletResponse

ServletRequest和ServletResponse是Servlet#service() 方法的兩個參數,一個是請求對象,一個是響應對象,可以從ServletRequest對象中獲取請求數據,可以使用ServletResponse對象完成響應。你以後會發現,這兩個對象就像是一對恩愛的夫妻,永遠不分離,總是成對出現。

ServletRequest和ServletResponse的實例由服務器創建,然後傳遞給service()方法。如果在service() 方法中希望使用HTTP相關的功能,那麼可以把ServletRequest和ServletResponse強轉成HttpServletRequest和HttpServletResponse。這也說明我們經常需要在service()方法中對ServletRequest和ServletResponse進行強轉,這是很心煩的事情。不過後面會有一個類來幫我們解決這一問題的。

HttpServletRequest方法:

String getParameter(String paramName):獲取指定請求參數的值 String getMethod():獲取請求方法,例如GET或POST String getHeader(String name):獲取指定請求頭的值 void setCharacterEncoding(String encoding):設置請求體的編碼

因為GET請求沒有請求體,所以這個方法隻隻對POST請求有效。當調用request.setCharacterEncoding(“utf-8”)之後,再通過getParameter()方法獲取參數值時,那麼參數值都已經通過瞭轉碼,即轉換成瞭UTF-8編碼。所以,這個方法必須在調用getParameter()方法之前調用!

HttpServletResponse方法:

PrintWriter getWriter()
獲取字符響應流,使用該流可以向客戶端輸出響應信息。例如response.getWriter().print(“

Hello JavaWeb!

”)

 

ServletOutputStream getOutputStream()
獲取字節響應流,當需要向客戶端響應字節數據時,需要使用這個流,例如要向客戶端響應圖片

void setCharacterEncoding(String encoding)
用來設置字符響應流的編碼,例如在調用setCharacterEncoding(“utf-8”);之後,再response.getWriter()獲取字符響應流對象,這時的響應流的編碼為utf-8,使用response.getWriter()輸出的中文都會轉換成utf-8編碼後發送給客戶端

void setHeader(String name, String value)
向客戶端添加響應頭信息,例如setHeader(“Refresh”, “3;url=https://www.itcast.cn”),表示3秒後自動刷新到https://www.itcast.cn

void setContentType(String contentType)
該方法是setHeader(“content-type”, “xxx”)的簡便方法,即用來添加名為content-type響應頭的方法。content-type響應頭用來設置響應數據的MIME類型,例如要向客戶端響應jpg的圖片,那麼可以setContentType(“image/jepg”),如果響應數據為文本類型,那麼還要臺同時設置編碼,例如setContentType(“text/html;chartset=utf-8”)表示響應數據類型為文本類型中的html類型,並且該方法會調用setCharacterEncoding(“utf-8”)方法

void sendError(int code, String errorMsg):向客戶端發送狀態碼,以及錯誤消息。例如給客戶端發送404:response(404, “您要查找的資源不存在!”)

2.1 ServletConfig

ServletConfig對象對應web.xml文件中的元素。例如你想獲取當前Servlet在web.xml文件中的配置名,那麼可以使用servletConfig.getServletName()方法獲取!

ServletConfig對象是由服務器創建的,然後傳遞給Servlet的init()方法,你可以在init()方法中使用它!

String getServletName():獲取Servlet在web.xml文件中的配置名稱,即指定的名稱 ServletContext getServletContext():用來獲取ServletContext對象,ServletContext會在後面講解 String getInitParameter(String name):用來獲取在web.xml中配置的初始化參數,通過參數名來獲取參數值 Enumeration getInitParameterNames():用來獲取在web.xml中配置的所有初始化參數名稱

在元素中還可以配置初始化參數:

 
  One
  cn.itcast.servlet.OneServlet
  
      paramName1
          paramValue1
  
  
          paramName2
          paramValue2
  

在OneServlet中,可以使用ServletConfig對象的getInitParameter()方法來獲取初始化參數,例如:

String value1 = servletConfig.getInitParameter(“paramName1”);//獲取到paramValue1

GenericServlet

1、GenericServlet概述

GenericServlet是Servlet接口的實現類,我們可以通過繼承GenericServlet來編寫自己的Servlet。下面是GenericServlet類的源代碼:

GenericServlet.java

public abstract class GenericServlet implements Servlet, ServletConfig,
        java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;
    public GenericServlet() {}
    @Override
    public void destroy() {}
    @Override
    public String getInitParameter(String name) {
        return getServletConfig().getInitParameter(name);
    }
    @Override
    public Enumeration getInitParameterNames() {
        return getServletConfig().getInitParameterNames();
    }
    @Override
    public ServletConfig getServletConfig() {
        return config;
    }
    @Override
    public ServletContext getServletContext() {
        return getServletConfig().getServletContext();
    }
    @Override
    public String getServletInfo() {
        return "";
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
    public void init() throws ServletException {}
    public void log(String msg) {
        getServletContext().log(getServletName() + ": " + msg);
    }
    public void log(String message, Throwable t) {
        getServletContext().log(getServletName() + ": " + message, t);
    }
    @Override
    public abstract void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException;
    @Override
    public String getServletName() {
        return config.getServletName();
    }
}

2、GenericServlet的init()方法

在GenericServlet中,定義瞭一個ServletConfig config實例變量,並在init(ServletConfig)方法中把參數ServletConfig賦給瞭實例變量。然後在該類的很多方法中使用瞭實例變量config。

如果子類覆蓋瞭GenericServlet的init(StringConfig)方法,那麼this.config=config這一條語句就會被覆蓋瞭,也就是說GenericServlet的實例變量config的值為null,那麼所有依賴config的方法都不能使用瞭。如果真的希望完成一些初始化操作,那麼去覆蓋GenericServlet提供的init()方法,它是沒有參數的init()方法,它會在init(ServletConfig)方法中被調用。

3、實現瞭ServletConfig接口

GenericServlet還實現瞭ServletConfig接口,所以可以直接調用getInitParameter()、getServletContext()等ServletConfig的方法。

HttpServlet

1、HttpServlet概述

HttpServlet類是GenericServlet的子類,它提供瞭對HTTP請求的特殊支持,所以通常我們都會通過繼承HttpServlet來完成自定義的Servlet。

2、HttpServlet覆蓋瞭service()方法

HttpServlet類中提供瞭service(HttpServletRequest,HttpServletResponse)方法,這個方法是HttpServlet自己的方法,不是從Servlet繼承來的。在HttpServlet的service(ServletRequest,ServletResponse)方法中會把ServletRequest和ServletResponse強轉成HttpServletRequest和HttpServletResponse,然後調用service(HttpServletRequest,HttpServletResponse)方法,這說明子類可以去覆蓋service(HttpServletRequest,HttpServletResponse)方法即可,這就不用自己去強轉請求和響應對象瞭。

其實子類也不用去覆蓋service(HttpServletRequest,HttpServletResponse)方法,因為HttpServlet還要做另一步簡化操作,下面會介紹。

HttpServlet.java

public abstract class HttpServlet extends GenericServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        ……
}
    @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }
        service(request, response);
}
……
}

3、doGet()和doPost()

在HttpServlet的service(HttpServletRequest,HttpServletResponse)方法會去判斷當前請求是GET還是POST,如果是GET請求,那麼會去調用本類的doGet()方法,如果是POST請求會去調用doPost()方法,這說明我們在子類中去覆蓋doGet()或doPost()方法即可。

public class AServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("hello doGet()...");
    }
}
public class BServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("hello doPost()...");
    }
}

Servlet細節

不要在Servlet中創建成員!創建局部變量即可! 可以創建無狀態成員! 可以創建有狀態的成員,但狀態必須為隻讀的!

1、Servlet與線程安全

因為一個類型的Servlet隻有一個實例對象,那麼就有可能會現時出一個Servlet同時處理多個請求,那麼Servlet是否為線程安全的呢?答案是:“不是線程安全的”。這說明Servlet的工作效率很高,但也存在線程安全問題!

所以我們不應該在Servlet中隨便創建成員變量,因為可能會存在一個線程對這個成員變量進行寫操作,另一個線程對這個成員變量進行讀操作。

2、讓服務器在啟動時就創建Servlet

默認情況下,服務器會在某個Servlet第一次收到請求時創建它。也可以在web.xml中對Servlet進行配置,使服務器啟動時就創建Servlet。


    hello1
    cn.itcast.servlet.Hello1Servlet
    0


    hello1
    /hello1


    hello2
    cn.itcast.servlet.Hello2Servlet
    1


    hello2
    /hello2


    hello3
    cn.itcast.servlet.Hello3Servlet
    2


    hello3
    /hello3

在元素中配置元素可以讓服務器在啟動時就創建該Servlet,其中元素的值必須是大於等於的整數,它的使用是服務器啟動時創建Servlet的順序。上例中,根據的值可以得知服務器創建Servlet的順序為Hello1Servlet、Hello2Servlet、Hello3Servlet。

3、

是的子元素,用來指定Servlet的訪問路徑,即URL。它必須是以“/”開頭!

3.1 可以在中給出多個,例如:


  AServlet
  /AServlet
  /BServlet
  

那麼這說明一個Servlet綁定瞭兩個URL,無論訪問/AServlet還是/BServlet,訪問的都是AServlet。

3.2 還可以在中使用通配符,所謂通配符就是星號“*”,星號可以匹配任何URL前綴或後綴,使用通配符可以命名一個Servlet綁定一組URL,例如:

/servlet/:/servlet/a、/servlet/b,都匹配/servlet/.do:/abc/def/ghi.do、/a.do,都匹配.do; /*:匹配所有URL;

請註意,通配符要麼為前綴,要麼為後綴,不能出現在URL中間位置,也不能隻有通配符。例如:/.do就是錯誤的,因為星號出現在URL的中間位置上瞭。.*也是不對的,因為一個URL中最多隻能出現一個通配符。

註意,通配符是一種模糊匹配URL的方式,如果存在更具體的,那麼訪問路徑會去匹配具體的。例如:


        hello1
        cn.itcast.servlet.Hello1Servlet
    
    
        hello1
        /servlet/hello1
    
    
        hello2
        cn.itcast.servlet.Hello2Servlet
    
    
        hello2
        /servlet/*
    

當訪問路徑為https://localhost:8080/hello/servlet/hello1時,因為訪問路徑即匹配hello1的,又匹配hello2的,但因為hello1的中沒有通配符,所以優先匹配,即設置hello1。

4、web.xml文件的繼承

在${CATALINA_HOME}\conf\web.xml中的內容,相當於寫到瞭每個項目的web.xml中,它是所有web.xml的父文件。

每個完整的JavaWeb應用中都需要有web.xml,但我們不知道所有的web.xml文件都有一個共同的父文件,它在Tomcat的conf/web.xml路徑。

conf/web.xml




     
        default
        org.apache.catalina.servlets.DefaultServlet
        
            debug
            0
        
        
            listings
            false
        
        1


    
        jsp
        org.apache.jasper.servlet.JspServlet
        
            fork
            false
        
        
            xpoweredBy
            false
        
        3
    

    
        default
        /
    

    
        jsp
        *.jsp
        *.jspx
    

    
        30
    

    
    
        bmp
        image/bmp
    
    
        htm
        text/html
    

    
        index.html
        index.htm
        index.jsp
    

ServletContext

一個項目隻有一個ServletContext對象!

我們可以在N多個Servlet中來獲取這個唯一的對象,使用它可以給多個Servlet傳遞數據!

與天地同壽!!!這個對象在Tomcat啟動時就創建,在Tomcat關閉時才會死去!

1、ServletContext概述

服務器會為每個應用創建一個ServletContext對象:

ServletContext對象的創建是在服務器啟動時完成的;

ServletContext對象的銷毀是在服務器關閉時完成的。

ServletContext對象的作用是在整個Web應用的動態資源之間共享數據!例如在AServlet中向ServletContext對象中保存一個值,然後在BServlet中就可以獲取這個值,這就是共享數據瞭。

2、獲取ServletContext

ServletConfig#getServletContext(); GenericServlet#getServletContext(); HttpSession#getServletContext() ServletContextEvent#getServletContext()

在Servlet中獲取ServletContext對象:

在void init(ServletConfig config)中:ServletContext context = config.getServletContext();,ServletConfig類的getServletContext()方法可以用來獲取ServletContext對象

在GenericeServlet或HttpServlet中獲取ServletContext對象:

GenericServlet類有getServletContext()方法,所以可以直接使用this.getServletContext()來獲取

public class MyServlet implements Servlet {
public void init(ServletConfig config) {
    ServletContext context = config.getServletContext();
}
…
}
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    ServletContext context = this.getServletContext();
}
}

3、域對象的功能

ServletContext是JavaWeb四大域對象之一:

PageContext; ServletRequest; HttpSession; ServletContext;

所有域對象都有存取數據的功能,因為域對象內部有一個Map,用來存儲數據,下面是ServletContext對象用來操作數據的方法:

void setAttribute(String name, Object value)
用來存儲一個對象,也可以稱之為存儲一個域屬性,例如:servletContext.setAttribute(“xxx”, “XXX”),在ServletContext中保存瞭一個域屬性,域屬性名稱為xxx,域屬性的值為XXX。請註意,如果多次調用該方法,並且使用相同的name,那麼會覆蓋上一次的值,這一特性與Map相同

Object getAttribute(String name)
用來獲取ServletContext中的數據,當前在獲取之前需要先去存儲才行,例如:String value = (String)servletContext.getAttribute(“xxx”);,獲取名為xxx的域屬性

void removeAttribute(String name)
用來移除ServletContext中的域屬性,如果參數name指定的域屬性不存在,那麼本方法什麼都不做

Enumeration getAttributeNames():獲取所有域屬性的名稱

4、獲取應用初始化參數

Servlet也可以獲取初始化參數,但它是局部的參數;也就是說,一個Servlet隻能獲取自己的初始化參數,不能獲取別人的,即初始化參數隻為一個Servlet準備!

可以配置公共的初始化參數,為所有Servlet而用!這需要使用ServletContext才能使用!

還可以使用ServletContext來獲取在web.xml文件中配置的應用初始化參數!註意,應用初始化參數與Servlet初始化參數不同:

web.xml


  ...
  
    paramName1
    paramValue1      
  
  
    paramName2
    paramValue2      
  
ServletContext context = this.getServletContext();
String value1 = context.getInitParameter("paramName1");
String value2 = context.getInitParameter("paramName2");
System.out.println(value1 + ", " + value2);

Enumeration names = context.getInitParameterNames();
while(names.hasMoreElements()) {
        System.out.println(names.nextElement());
}

5、獲取資源相關方法

5.1 獲取真實路徑

還可以使用ServletContext對象來獲取Web應用下的資源,例如在hello應用的根目錄下創建a.txt文件,現在想在Servlet中獲取這個資源,就可以使用ServletContext來獲取。

獲取a.txt的真實路徑:String realPath = servletContext.getRealPath(“/a.txt”),realPath的值為a.txt文件的絕對路徑:F:\tomcat6\webapps\hello\a.txt; 獲取b.txt的真實路徑:String realPath = servletContext.getRealPath(“/WEB-INF/b.txt”);

5.2 獲取資源流

不隻可以獲取資源的路徑,還可以通過ServletContext獲取資源流,即把資源以輸入流的方式獲取:

獲取a.txt資源流:InputStream in = servletContext.getResourceAsStream(“/a.txt”); 獲取b.txt資源流:InputStream in = servletContext.getResourceAsStream(“/WEB-INF/b.txt”);

5.3 獲取指定目錄下所有資源路徑

還可以使用ServletContext獲取指定目錄下所有資源路徑,例如獲取/WEB-INF下所有資源的路徑:

Set set = context.getResourcePaths("/WEB-INF");
System.out.println(set);

[/WEB-INF/lib/, /WEB-INF/classes/, /WEB-INF/b.txt, /WEB-INF/web.xml]

註意,本方法必須以“/”開頭!!!

6、練習:訪問量統計

一個項目中所有的資源被訪問都要對訪問量進行累加!
創建一個int類型的變量,用來保存訪問量,然後把它保存到ServletContext的域中,這樣可以保存所有的Servlet都可以訪問到!

最初時,ServletContext中沒有保存訪問量相關的屬性; 當本站第一次被訪問時,創建一個變量,設置其值為1;保存到ServletContext中;

當以後的訪問時,就可以從ServletContext中獲取這個變量,然後在其基礎之上加1。

獲取ServletContext對象,查看是否存在名為count的屬性,如果存在,說明不是第一次訪問,如果不存在,說明是第一次訪問;

第一次訪問:調用Servletcontext的setAttribute()傳遞一個屬性,名為count,值為1; 第2~N次訪問:調用ServletContext的getAttribute()方法獲取原來的訪問量,給訪問量加1,再調用Servletcontext的setAttribute()方法完成設置。

相信各位一定見過很多訪問量統計的網站,即“本頁面被訪問過XXX次”。因為無論是哪個用戶訪問指定頁面,都會累計訪問量,所以這個訪問量統計應該是整個項目共享的!很明顯,這需要使用ServletContext來保存訪問量。

    ServletContext application  = this.getServletContext();
        Integer count = (Integer)application.getAttribute("count");
        if(count == null) {
            count = 1;
        } else {
            count++;
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("

本頁面一共被訪問" + count + "次!

"); application.setAttribute("count", count);

獲取類路徑下資源

獲取類路徑資源,類路徑對一個JavaWeb項目而言,就是/WEB-INF/classes和/WEB-INF/lib/每個jar包!

Class ClassLoader:

這裡要講的是獲取類路徑下的資源,對於JavaWeb應用而言,就是獲取classes目錄下的資源。

InputStream in = this.getClass().getResourceAsStream("/xxx.txt");
        System.out.println(IOUtils.toString(in));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("xxx.txt");
        System.out.println(IOUtils.toString(in));

Class類的getResourceAsStream(String path):
路徑以“/”開頭,相對classes路徑; 路徑不以“/”開頭,相對當前class文件所有路徑,例如在cn.itcast.servlet.MyServlet中執行,那麼相對/classes/cn/itcast/servlet/路徑; ClassLoader類的getResourceAsStream(String path):
相對classes路徑;

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *