Servlet学习笔记--统计网站的访问量(jsp/servlet)

一、步骤
1、创建Servlet类,用于统计用户访问次数
2、在wel.xml中配置Servlet类

二、
之前在试过在jsp页面实现相同的功能,代码也很相似,现在整理一下,做做笔记(^__^)

三、相关代码
1、在jsp页面上显示浏览量
方法:在jsp页面中获取application对象。
关键代码(部):

<%
        //统计网页访问量
        if (application.getAttribute("count") == null) {    
            application.setAttribute("count", 0);//application.setAttribute("count", new Integer(0));
        }
        Integer count = (Integer) application.getAttribute("count");
        //使用application对象读取count参数的值,再在原值基础上累加1     
        application.setAttribute("count", count + 1);//application.setAttribute("count", new Integer(count.intValue() + 1));
%>
    <h2>
        
        欢迎您访问,本页面已经被访问过 <font color="#ff0000"><%=application.getAttribute("count")%>font>次
    h2>

2、用Servlet类实现统计网页访问量
1)CounterServlet.jsp

package com.code;

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 CounterServlet extends HttpServlet {

    private static final long serialVersionUID = 942182270491996283L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = getServletContext();//获取ServletContext对象
        Integer count = (Integer) context.getAttribute("counter");//获取计数对象
        if(count == null){
            count = 1;
            context.setAttribute("counter", count);
        }else{
            context.setAttribute("counter", count+1);
        }
        response.setContentType("text/html;charset=utf-8");//设置response的编码
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("  统计网站访问次数");
        out.println("  ");
        out.println("

您是"+context.getAttribute("counter")+"位访客!

"
); out.println(" "); out.println(""); out.flush(); out.close(); } }

2)wex.xml配置

  <servlet>
    <servlet-name>CounterServletservlet-name>
    <servlet-class>com.code.CounterServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>CounterServletservlet-name>
    <url-pattern>CounterServleturl-pattern>
  servlet-mapping>

你可能感兴趣的:(servlet)