天天看點

Spring Boot入門(12)實作頁面通路量統計功能

  在日常的網站使用中,經常會碰到頁面的通路量(或者通路者人數)統計。那麼,在Spring Boot中該如何實作這個功能呢?

  我們的想法是比較簡單的,那就是将通路量儲存在某個地方,要用的時候取出來即可,儲存的位置可選擇資料庫或者其他檔案。本例所使用的例子為txt檔案,我們将通路量資料記錄在D盤的count.txt檔案中。

  下面直接開始本次的項目。整個項目的完整結構如下:

我們隻需要修改劃紅線的三個檔案,其中build.gradle的代碼如下:

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.0.1.RELEASE'
}           

視圖檔案(模闆)index.HTML的代碼如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>通路統計</title>
    <script th:inline="javascript">
        function load(){
            var count = [[${count}]];
            document.getElementById("visit").innerHTML = count.toString();
        }
    </script>
</head>
<body onload="load()">
<h1>Hello, world!</h1>
<p>&emsp;&emsp;本頁面已被通路<span id="visit"></span>次。</p>
</body>
</html>           

控制器檔案VisitController.java檔案的代碼如下:

package com.example.visit.Controller;

import java.io.*;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class VisitController {

    @GetMapping("/index")
    public String Index(Map <String, Object> map){
        // 擷取通路量資訊
        String txtFilePath = "D://count.txt";
        Long count = Get_Visit_Count(txtFilePath);
        System.out.println(count);
        map.put("count", count); // 背景參數傳遞給前端

        return "index";
    }

    /*
     * 擷取txt檔案中的數字,即之前的通路量
     * 傳入參數為: 字元串: txtFilePath,檔案的絕對路徑
     */
    public static Long Get_Visit_Count(String txtFilePath) {

        try {
            //讀取檔案(字元流)
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(txtFilePath),"UTF-8"));
            //循環讀取資料
            String str = null;
            StringBuffer content = new StringBuffer();
            while ((str = in.readLine()) != null) {
                content.append(str);
            }
            //關閉流
            in.close();

            //System.out.println(content);
            // 解析擷取的資料
            Long count = Long.valueOf(content.toString());
            count ++; // 通路量加1
            //寫入相應的檔案
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFilePath),"UTF-8"));
            out.write(String.valueOf(count));

            //清楚緩存
            out.flush();
            //關閉流
            out.close();

            return count;
        }
        catch (Exception e){
            e.printStackTrace();
            return 0L;
        }


    }
}
           

這樣我們就完成了整個項目的配置,最後,我們在D盤中的count.txt中寫入數字0,作為初始通路量。

  運作Spring Boot項目,在浏覽器中輸入localhost:8080/index , 顯示的頁面如下:

剛載入頁面時,顯示頁面被通路1次。當我們将這個這也載入10次後,顯示如下:

這樣我們就用Spring Boot實作了頁面通路量的統計功能。

  本次分享到此結束,歡迎大家交流~~

注意:本人現已開通兩個微信公衆号: 因為Python(微信号為:python_math)以及輕松學會Python爬蟲(微信号為:easy_web_scrape), 歡迎大家關注哦~~