使用ServletContext对象统计网站的访问量

来源:互联网 发布:可以看亚丝娜本子软件 编辑:程序博客网 时间:2024/04/30 20:43


功能

实现访问网站总人数的记录,以及基于某一特定起点的访问记录。

方案

由于网站中的资源较多,要想保留每一次的访问计数则需要一个从应用已启动就存在的空间,并且应用中的所有资源都能访问到这个存储空间,所有使用ServletContext及Servlet上下文对象保存每一次的访问计数。

步骤

Step1:新建Context01Servlet.java和Context02Servlet.java文件
两个文件内容一致,获取上下文对象后判断是否是第一次访问,是第一次则初始值为1,不是则增加1.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<codeclass="hljs java">packageweb;
 
importjava.io.IOException;
importjava.io.PrintWriter;
 
importjavax.servlet.ServletContext;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
 
publicclass Context01Servlet extendsHttpServlet{
    @Override
    protectedvoid service(HttpServletRequest request,
            HttpServletResponse response)
            throwsServletException,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"));
    }
}
</code>

Step2 : 配置web.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<codeclass="hljs java"><codeclass="hljs 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>
</code></code>

step3: 部署运行

0 0
原创粉丝点击