在日常的網站使用中,經常會碰到頁面的訪問量(或者訪問者人數)統計。那么,在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>  本頁面已被訪問<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), 歡迎大家關注哦~~