1. 程式人生 > >WEB專案-通過ServletContext物件來統計網站的訪問次數

WEB專案-通過ServletContext物件來統計網站的訪問次數

package com.servlet;

import java.io.IOException;

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;

/*
 * 從ServletContext物件中獲取值,然後再存入值
 */

@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void init() throws ServletException {
		ServletContext context = this.getServletContext();
		//向ServletContext物件中存入變數,初始值為0
		//設定一個變數
		context.setAttribute("count",0);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ServletContext context = this.getServletContext();
		//從context中獲取count,並且自增加一
		//取出變數
		Integer count = (Integer) context.getAttribute("count");
		//讓count自加1
		count++;
		//覆蓋之前count的值
		context.setAttribute("count", count);
		//將count的值顯示到頁面上
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("訪問次數:"+count);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}