You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Spring应用集成Google Analytics报表图表的步骤咨询

Java Spring管理模块集成Google Analytics自定义报表图表的分步指引

一、GA API授权与项目配置

1. 创建GA服务账号并获取密钥

  • 登录Google Cloud控制台,创建新服务账号并关联你的GA4资源
  • 为服务账号分配Analytics Data Viewer权限,确保具备GA数据读取权限
  • 下载服务账号的JSON密钥文件,放到Spring项目的resources目录下(建议重命名为ga-service-account.json)

2. 添加GA客户端依赖

在项目pom.xml中引入GA数据API依赖:

<dependency>
    <groupId>com.google.analytics</groupId>
    <artifactId>google-analytics-data</artifactId>
    <version>v1beta-rev20240314-2.0.0</version>
</dependency>

3. 配置应用参数

在application.properties中添加GA相关配置项:

# GA4 Property ID(在GA后台查看)
ga.property.id=YOUR_GA_PROPERTY_ID
# 服务账号密钥文件路径
ga.service.account.key.path=classpath:ga-service-account.json

二、编写GA数据查询服务

创建服务类封装GA数据查询逻辑:

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.DateRange;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.RunReportRequest;
import com.google.analytics.data.v1beta.RunReportResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;

@Service
public class GaReportService {

    @Value("${ga.property.id}")
    private String propertyId;

    @Value("${ga.service.account.key.path}")
    private String keyPath;

    public RunReportResponse getUserRoleLoginReport() throws IOException {
        // 初始化GA数据客户端
        try (BetaAnalyticsDataClient analyticsDataClient = BetaAnalyticsDataClient.createWithServiceAccount(
                new FileInputStream(keyPath.substring(10)))) { // 移除classpath:前缀
            RunReportRequest request = RunReportRequest.newBuilder()
                    .setProperty("properties/" + propertyId)
                    // 匹配自定义报表的维度:用户ID、角色、访问日期
                    .addDimensions(Dimension.newBuilder().setName("customEvent:user_id"))
                    .addDimensions(Dimension.newBuilder().setName("customEvent:user_role"))
                    .addDimensions(Dimension.newBuilder().setName("date"))
                    // 指标:登录次数(对应GTM中发送的登录事件计数)
                    .addMetrics(Metric.newBuilder().setName("eventCount"))
                    // 设置日期范围,可按需调整
                    .addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("today"))
                    .build();

            return analyticsDataClient.runReport(request);
        }
    }
}

三、开发后端接口

编写Controller提供数据接口供前端调用:

import com.google.analytics.data.v1beta.RunReportResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/admin/ga-reports")
public class GaReportController {

    private final GaReportService gaReportService;

    public GaReportController(GaReportService gaReportService) {
        this.gaReportService = gaReportService;
    }

    @GetMapping("/user-role-login")
    public RunReportResponse getUserRoleLoginData() throws IOException {
        return gaReportService.getUserRoleLoginReport();
    }
}

四、前端页面渲染(以Thymeleaf + Chart.js为例)

1. 引入依赖资源

在管理页面<head>中加入Chart.js:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

2. 页面结构

添加图表容器与数据表格:

<div class="admin-report">
    <h3>用户角色登录统计</h3>
    <canvas id="loginChart" width="400" height="200"></canvas>
    <table id="loginTable" class="table table-striped">
        <thead>
            <tr>
                <th>用户ID</th>
                <th>角色</th>
                <th>访问日期</th>
                <th>登录次数</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

3. 编写JS请求并渲染数据

document.addEventListener('DOMContentLoaded', function() {
    // 请求GA报表数据
    fetch('/admin/ga-reports/user-role-login')
        .then(response => response.json())
        .then(data => {
            // 处理图表数据
            const labels = data.rows.map(row => row.dimensionValues[2].value); // 提取访问日期
            const datasets = [];
            // 按角色分组整理数据
            const roleDataMap = {};
            data.rows.forEach(row => {
                const role = row.dimensionValues[1].value;
                const count = parseInt(row.metricValues[0].value);
                if (!roleDataMap[role]) roleDataMap[role] = {};
                roleDataMap[role][row.dimensionValues[2].value] = count;
            });
            // 转换为Chart.js兼容格式
            Object.keys(roleDataMap).forEach(role => {
                datasets.push({
                    label: role,
                    data: labels.map(date => roleDataMap[role][date] || 0),
                    borderColor: getRandomColor(),
                    fill: false
                });
            });
            // 渲染折线图
            new Chart(document.getElementById('loginChart'), {
                type: 'line',
                data: { labels, datasets },
                options: {
                    responsive: true,
                    scales: { y: { beginAtZero: true } }
                }
            });

            // 渲染数据表格
            const tbody = document.getElementById('loginTable').querySelector('tbody');
            data.rows.forEach(row => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${row.dimensionValues[0].value}</td>
                    <td>${row.dimensionValues[1].value}</td>
                    <td>${row.dimensionValues[2].value}</td>
                    <td>${row.metricValues[0].value}</td>
                `;
                tbody.appendChild(tr);
            });
        })
        .catch(error => console.error('加载GA报表失败:', error));
});

// 生成随机图表颜色
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

五、权限控制

通过Spring Security限制仅管理员角色可访问:

@RestController
@RequestMapping("/admin/ga-reports")
@PreAuthorize("hasRole('ADMIN')")
public class GaReportController {
    // 原有接口代码
}

页面模板中添加权限验证:

<div sec:authorize="hasRole('ADMIN')" class="admin-report">
    <!-- 报表内容 -->
</div>

内容的提问来源于stack exchange,提问作者Prabhash Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:10:36