从片段调用时遇到 thymeleaf 属性问题

问题描述 投票:0回答:0

我不知道问题出在哪里。问题出现在百里香碎片上。

让我逐部分描述问题。

  1. home.html 此 html 是根页面。因为所有片段都会放在home页面上。
  2. HomeController.java这是用于控制home.html的控制器。
  3. credential.html 此 html 是一个片段,该页面将插入到主页上。但是,当我尝试使用 thymeleaf 属性使用控制器执行操作时,它在主页上不显示任何内容。当我尝试不使用 thymeleaf 属性时,它开始工作。为什么?我也尝试在网上查看一些资源,但没有一个对我的需求有用
  4. CredentialController.java凭证视图控制器。

home.html

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1  th:each="msg : ${greetings}" th:text="${msg}" th:unless="${msg.contains('Hello')}">Hello, homepage!</h1>
<h2 th:each=" i : ${n} " th:text="${i}" th:unless="${i.contains('1')}">For loop</h2>

<div th:insert="fragments/create-credential :: credential"></div>
</body>
</html>

HomeController.java

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.ArrayList;
    
    @Controller
    @RequestMapping("/home")
    public class HomeController {
        @GetMapping
        public String action(Model model){
            model.addAttribute("greetings", new String[] {"Hello","What's up","Now it's Okey"});
    
            model.addAttribute("n",new String[] {"1","2","3"});
            return "home";
        }
}

创建凭证.html

<!doctype html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div class="container" th:fragment="credential">
    <h1 th:text="${hello}">Got the problem</h1>
</div>
</body>
</html>

CredentialController.java

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

@Controller
@RequestMapping("/create-credential")
public class CredentialController {
    @GetMapping
    public String anotherAction(Model model){
        model.addAttribute("hello","Got the problem");
        return "create-credential";
    }
}

令我没想到的是:

这就是我所期望的:

spring-boot spring-mvc thymeleaf
© www.soinside.com 2019 - 2024. All rights reserved.