Servlet----------用servlet写一个“网站访问量统计“的小案例
1 package cn.example; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletContext; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 /** 12 * 网站访问量统计小案例 13 * @author LZC 14 */ 15 public class CallCount extends HttpServlet { 16 17 public void doGet(HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException { 19 /* 20 *1、获取ServletContext对象 21 *2、从ServletContext对象中获取名为count的属性用来保存访问量 22 *3、如果存在,则保存回去 23 *4、如果不存在,说明是第一次访问,向ServletContext中保存名为count的属性,值 为1 24 */ 25 response.setCharacterEncoding("GBK"); 26 ServletContext application =this.getServletContext(); 27 Integer count = (Integer) application.getAttribute("count"); 28 if(count==null){ 29 application.setAttribute("count", 1); 30 }else{ 31 application.setAttribute("count", count+1); 32 } 33 34 // 向浏览器输出,需要使用响应请求 35 response.setContentType("text/html"); 36 PrintWriter out = response.getWriter(); 37 out.println("<h2>您一共访问了 "+count+" 次</h2>"); 38 } 39 }