開發者學堂課程【Servlet 入門:網站通路量統計小案例】學習筆記,與課程緊密聯系,讓使用者快速學習知識。
課程位址:
https://developer.aliyun.com/learning/course/34/detail/757網站通路量統計小案例
内容介紹
一、網站通路量統計小案例
練習:通路量統計
一個項目中所有的資源被通路都要對通路量進行累加!
建立一個 int 類型的變量,用來儲存通路量,然後把它儲存到 SerletCentet 的域中,這樣可以儲存所有的 Servlet 都可以通路到!
*最初時,SenletContext 中沒有儲存通路量相關的屬性;
*當本站第一次被通路時,建立一個變量,設定其值為1;儲存到 SeCotet 中;
*當以後的通路時,就可以從 sevletCentet 中擷取這個變量,然後在其基礎之上加1。*.擷取 ServletContext 對象,檢視是否存在名為 count 的屬性,如果存在,說明不是第一次通路,如果不存在,說明是第一-次通路;
第一次通路:調用 Servletcontex t的 setAttribute 傳遞一個屬性,名為 count, 值為1;
第2~N次通路:調用 SendetContext 的 getAttribute(方法獲權原來的通路量,給通路量加1,再調用 Servletcontext 的 setAttribute 方法完成設定。
相信一定見過很多通路量統計的網站,即“本頁面被通路過xxx次”。因為無論是哪個使用者通路指定頁面,都會累計通路量,是以這個通路量統計應該是整個項目共享的!很明顯,這需要使用 ServletContext 來儲存通路量。
servletContext application
=this.getSexyhetContext()
Integer count
=(Integer) applicatdon.getattribute ("count")]:
if(count == nall) {
count = 1)
} else {
count++
}
sesponse. setContentTxee ("text/huml.charset
=utf-8");
Eesponse.getWriter() print ("
本頁面一共被通路" + count + “次!
”);
epplication. setAttribute ("count", count) ;
例如:
public class AServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
1. 擷取 ServletContext 對象
2. 從 ServletContext 對象中擷取名為 count 的屬性
3. 如果存在:給通路量加1,然後再儲存回去;
4.如果不存在:說明是第一次通路,向 Servletcontext 中儲存名為 count 的屬性,值為1
servletContext app = this.getServletcontext ();
Integer count = (Integer) app. getAttribute ("count");
if(count y null) {
app. etAttribute ("count", 1);
else (
app. setAttribute ("count", count+1);
向浏覽器輸出
需要使用響應對象!
PrintWriter pw = response getWriter() ;
pw-print("
" + count + "
") ;