SpringBoot⼊门(12)实现页⾯访问量统计功能
在⽇常的⽹站使⽤中,经常会碰到页⾯的访问量(或者访问者⼈数)统计。那么,在Spring Boot中该如何实现这个功能呢?
我们的想法是⽐较简单的,那就是将访问量储存在某个地⽅,要⽤的时候取出来即可,储存的位置可选择数据库或者其他⽂件。本例所使⽤的例⼦为txt⽂件,我们将访问量数据记录在D盘的⽂件中。
下⾯直接开始本次的项⽬。整个项⽬的完整结构如下:
我们只需要修改划红线的三个⽂件,其中adle的代码如下:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
springboot结构}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'ample'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
// mvnrepository/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="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>访问统计</title>
<script th:inline="javascript">
function load(){
var count = [[${count}]];
}
</script>
</head>
<body onload="load()">
<h1>Hello, world!</h1>
<p> &emsp;本页⾯已被访问<span id="visit"></span>次。</p>
</body>
</html>
控制器⽂件VisitController.java⽂件的代码如下:
ample.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://";
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.String());
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盘中的中写⼊数字0,作为初始访问量。
运⾏Spring Boot项⽬,在浏览器中输⼊localhost:8080/index , 显⽰的页⾯如下:
刚载⼊页⾯时,显⽰页⾯被访问1次。当我们将这个这也载⼊10次后,显⽰如下:
这样我们就⽤Spring Boot实现了页⾯访问量的统计功能。
本次分享到此结束,欢迎⼤家交流~~
注意:本⼈现已开通两个: 因为Python(号为:python_math)以及轻松学会Python爬⾍(号为:easy_web_scrape), 欢迎⼤家关注哦~~
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论