使用ServletContext物件統計網站的訪問量
阿新 • • 發佈:2019-01-10
- 功能
實現訪問網站總人數的記錄,以及基於某一特定起點的訪問記錄。
- 方案
由於網站中的資源較多,要想保留每一次的訪問計數則需要一個從應用已啟動就存在的空間,並且應用中的所有資源都能訪問到這個儲存空間,所有使用ServletContext及Servlet上下文物件儲存每一次的訪問計數。
- 步驟
Step1:新建Context01Servlet.java和Context02Servlet.java檔案
兩個檔案內容一致,獲取上下文物件後判斷是否是第一次訪問,是第一次則初始值為1,不是則增加1.
package web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Context01Servlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
//保證正確讀取Post提交來的中文
request.setCharacterEncoding("utf-8");
//保證正確輸出中文
response.setContentType("text/html;charset=utf-8");
//獲取輸出流物件,並輸出資訊
PrintWriter out=response.getWriter();
//獲取全域性的上下文物件
ServletContext context=getServletContext();
Object count=context.getAttribute("count");
if(count==null){
context.setAttribute("count", context.getInitParameter("count"));
//context.setAttribute("count", 1);
}else{
context.setAttribute("count", Integer.parseInt(count.toString())+1);
}
out.print("總瀏覽量為:"+context.getAttribute("count"));
}
}
Step2 : 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Servlet上下文 -->
<context-param>
<param-name>count</param-name>
<param-value>1000</param-value>
</context-param>
<servlet>
<servlet-name>context01Servlet</servlet-name>
<servlet-class>web.Context01Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>context01Servlet</servlet-name>
<url-pattern>/context01</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>context02Servlet</servlet-name>
<servlet-class>web.Context02Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>context02Servlet</servlet-name>
<url-pattern>/context02</url-pattern>
</servlet-mapping>
</web-app>
step3: 部署執行
=====================
關鍵知識點:
獲取Servlet上下文:
ServletContext context=getServletContext();
Object count=context.getAttribute(“count”);