1. 程式人生 > >JavaWeb基礎 ServletContext 服務器未關閉前,統計一個網頁的瀏覽次數

JavaWeb基礎 ServletContext 服務器未關閉前,統計一個網頁的瀏覽次數

ets images tis port his pin extend statistic attribute

禮悟:
   好好學習多思考,尊師重道存感恩。葉見尋根三二一,江河湖海同一體。
虛懷若谷良心主,願行無悔給最苦。讀書鍛煉強身心,誠勸且行且珍惜。




javaEE:7
javaSE:1.8
JSTL:1.2.2
server:tomcat 8.5
explorer:Firefox
os:windows7 x64
ide:MyEclipse 2017



工程目錄結構
技術分享


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

	<servlet>
		<servlet-name>StatisticsTimesServletContext</servlet-name>
		<servlet-class>jizuiku.web.servlet.StatisticsTimesServletContext</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>StatisticsTimesServletContext</servlet-name>
		<url-pattern>/StatisticsTimesServletContext</url-pattern>
	</servlet-mapping>
	
</web-app>

代碼

package jizuiku.web.servlet;

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;

/**
 * 在服務器關閉之前,統計該網頁的瀏覽量。
 * 
 * @author 給最苦
 * @version V17.10.21
 */
public class StatisticsTimesServletContext extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletContext application = this.getServletContext();
		// 有count返回值,沒有count返回Null
		Integer count = (Integer) application.getAttribute("count");

		if (count == null) {
			// 該網頁第一次訪問
			count = 1;
		} else {
			// 非第一次訪問
			count++;
		}

		// 存儲記錄
		application.setAttribute("count", count);

		// 向瀏覽器頁面輸出內容
		PrintWriter pw = response.getWriter();
		pw.print("<h1>" + count + "</h1>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

}

效果
技術分享

不刷新,再打開兩個該頁面
技術分享


學習資源:itcast和itheima視頻庫。如果您有公開的資源,可以分享給我的話,用您的資源學習也可以。
博文是觀看視頻後,融入思考寫成的。博文好,是老師講得好。博文壞,是 給最苦 沒認真。

JavaWeb基礎 ServletContext 服務器未關閉前,統計一個網頁的瀏覽次數