一个servlet例子-统计网站访问量

 
  

1.创建JavaWeb项目,名WebCount

2.修改web.xml,如下:



  WebCount1
 
    CounterServlet
    com.CounterServlet
 

 
    CounterServlet
    /counter
 

 
    counter
 

3.新建名称为CounterServlet的servlet类,在该类dopost()方法中实现统计访问数目。

package com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CounterServlet
 */
@WebServlet("/CounterServlet")
public class CounterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CounterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        super.destroy();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得ServletContext对象
        ServletContext context=getServletContext();
        //从ServletContext中获取计数器对象
        Integer count=(Integer) context.getAttribute("counter");
        if(count==null){//如果为空,则在ServletContext中设置一个计数器的属性
            count=1;
            context.setAttribute("counter", count);
        }else{
            context.setAttribute("counter", count+1);
        }
        
        response.setContentType("text/html");//响应正文的MIME类型
        response.setCharacterEncoding("UTF-8");//响应的编码格式
        PrintWriter out=response.getWriter();
//        out.println("");
//        out.println("");
//        out.println("");
        out.println("统计网站访问次数");
        out.println("");
//        out.println("

        out.println("您是第"+context.getAttribute("counter")+"位访客!");
//        out.println("
");
//        out.println("

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

}


4.将项目部署到服务器,启动服务器。结果如下。

一个servlet例子-统计网站访问量_第1张图片


你可能感兴趣的:(java,servlet)