当前位置: 首页 > 知识库问答 >
问题:

“th:text/each”不显示数据(Spring Boot/Thymeleaf)

施琦
2023-03-14

这个应用程序应该从网页上获取关于冠状病毒的信息,并将其输出到我们自己的网页上的一个漂亮的表格中。

所有表头都在,但列本身为空。

Tymeleaf在模型中不显示传递给它的数据,尽管数据在控制器中正确传递。我会很感激你的任何意见,谢谢。

package io.javabrains.coronavirustracker.models;

public class LocationStats
{
    private String state;
    private String country;
    private int latestTotalCases;

    public String getState() { return this.state; }

    public void setState(String state) { this.state = state; }

    public String getCountry() { return this.country; }

    public void setCountry(String country) { this.country = country; }

    public int getLatestTotalCases() { return this.latestTotalCases; }

    public void setLatestTotalCases(int latestTotalCases) { this.latestTotalCases = latestTotalCases; }

    @Override
    public String toString()
    {
        return "LocationStats{" + "state='" + state + '\'' + ", country='" + country + '\'' + ", latestTotalCases=" + latestTotalCases + '}';
    }
}

package io.javabrains.coronavirustracker.services;

import io.javabrains.coronavirustracker.models.LocationStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoronaVirusDataService
{
    private static String VIRUS_DATA_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private List<LocationStats> allStats = new ArrayList<>();

    public List<LocationStats> getAllStats() { return allStats; }

    @PostConstruct
    @Scheduled(cron = "* * 1 * * *")
    public void fetchVirusData() throws IOException, InterruptedException
    {
        List<LocationStats> newStats = new ArrayList<>();
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(VIRUS_DATA_URL)).build();
        HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(httpResponse.body()); // Prints all data as expected

        StringReader csvBodyReader = new StringReader(httpResponse.body());
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader);

        for(CSVRecord record : records)
        {
            LocationStats locationStat = new LocationStats();

            locationStat.setCountry(record.get("Country/Region"));
            locationStat.setState(record.get("Province/State"));
            locationStat.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
            newStats.add(locationStat);
            
            System.out.println(locationStat); // Prints data as expected
        }

        this.allStats = newStats;
    }
}
package io.javabrains.coronavirustracker.controllers;

import io.javabrains.coronavirustracker.models.LocationStats;
import io.javabrains.coronavirustracker.services.CoronaVirusDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class HomeController
{
    @Autowired
    CoronaVirusDataService coronaVirusDataService;

    @GetMapping("/")
    public String home(Model model)
    {
        List<LocationStats> allStats = coronaVirusDataService.getAllStats();
        int testNumber = 999; // For test attribute

        model.addAttribute("locationStats", allStats); // Actual attribute
        model.addAttribute("testInt", testNumber); // Test attribute

        return "home";
    }
}
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Corona Virus Tracker Application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>

<body>

<h1 th:text="${testInt}">-1</h1>

<table>
    <tr>
        <th>State</th>
        <th>Country</th>
        <th>Total Cases</th>

    </tr>
    <tr th:each="locationStat : ${locationStats}">
        <td th:text="${locationStat.state}"></td>
        <td th:text="${locationStat.country}"></td>
        <td th:text="${locationStat.latestTotalCases}">0</td>
    </tr>
</table>

</body>

</html>
package io.javabrains.coronavirustracker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class CoronavirusTrackerApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(CoronavirusTrackerApplication.class, args);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>io.javabrains</groupId>
    <artifactId>coronavirus-tracker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>coronavirus-tracker</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>14</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>14</source>
                    <target>14</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

共有1个答案

柳韬
2023-03-14
<td th:text="${locationStat.state}"></td>
 类似资料:
  • 问题内容: 我正在尝试填写从GET请求中收到的一些数据。我不知道为什么,但是如果在我的中,我返回一个特定的值(例如8),它表示信息。如果y返回请求填充的数组的值,则不添加任何行: 知道为什么会这样吗?非常感谢你!! 更新! 我解决了这个问题,在loadUserData()函数内的complete()之后添加了self.tableView.reloadData()。希望能帮助到你! 问题答案: 快速

  • 我正在尝试jQuery数据表控件。问题是我不能显示数据。 HTML是: 如果我注释掉Ajax代码并取消注释 它很好用。变量是我使用firefox从服务中获取的JSON数据- 我读了很多帖子,尝试了很多东西,但都没能成功。有什么帮助吗?谢谢 编辑:服务代码: 《编辑》20150721:我对HTML代码做了一些修改,但有一个小错误。加载时,我在页面顶部看到了table元素的标题(ActivityHis

  • 我想创建网站。我已经配置了登录“/login”和注册“/registration”页面。这个网站的主要任务是显示每个学生的时间表。现在我需要在页面“/Schedule”上显示科目列表,使用HTML-table,根据学生注册时选择的字段组和课程。我有14个不同的表格和科目列表(一个表格-一组学生)。 是否需要为每个表创建@Entity类和存储库? 如何使用注册数据显示学生信息? 页面“/计划”的控制

  • 应用程序运行良好...只是数据没有出现...我已经添加了sha用户电子邮件显示在登录后,在登录活动中我已经添加了 但是在实时数据库数据不显示以防万一…我也等了半个小时,尝试了所有的东西…网络也不错。数据库中的数据库规则的数据库图片 mainActivity.java//不能用于单个子级,即firebaseDatabase.getInstance().getReference().child(“aj

  • 我试图用自己的数据创建一个dataTable:代码如下: 但当我运行它时,我看到一张空桌子。我想查看我的数据,我怎么能?

  • 我编写这段代码是为了使用iReport 4.7.1显示一个简单的报告。 以下是我的库: commons-beanutils-1.8.0.jar commons-collections-2.1.1.jar commons-digester-2.1.jar commons-logging-1.1.1.jar jasperrreports-4.7.1.jar jasperreports-applet-4