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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM