首页 > 解决方案 > Thymeleaf 无法显示模型对象属性的值

问题描述

我是 Spring Boot 和 Thymeleaf 的新手。我创建了一个模拟设置,用于使用 Spring boot 学习 Thymeleaf。

在这里,我无法在 index.html 页面中看到 Model 属性的值。我无法在 html 页面中读取 Model 属性的值。下面是我写到现在的代码。

HelloWorldSpringBoot.java

package com.test.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloWorldSpringBoot {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldSpringBoot.class, args);
    }
}

你好世界控制器

package com.test.app.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

    @RequestMapping(value="/index")
    public String hello(Model model){
        model.addAttribute("test","value1");
        return "index";
    }
}

索引.html

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
   <h1 th:text="${test}"></h1>
</body>
</html>

应用程序属性

spring.thymeleaf.template-loader-path: classpath:/static/
spring.thymeleaf.suffix: .html
spring.thymeleaf.cache: false

Maven pm.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test.app</groupId>
  <artifactId>HelloWorldSpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  </dependencies>
</project>

项目结构

任何人都可以帮助我在 index.html 页面中显示值。

标签: javamavenspring-bootthymeleaf

解决方案


推荐阅读