【问题标题】:Thymleaf is not reading the model data returned from controllerThymeleaf 没有读取控制器返回的模型数据
【发布时间】:2018-07-20 09:52:27
【问题描述】:

Project Directory Structure

我是 Thymeleaf 的新手。这是一个简单的 HelloWorld 应用程序,我想在其中显示从控制器返回的 model 消息。它运行成功,但没有显示控制器返回的消息。
但是,当使用给定的 jsp 文件运行相同的代码时,它正在读取,这是很常见的事情。

WelcomeController 类是

@Controller
public class WelcomeController {
    private String pass="Welcome To ThymLeaf";

    @RequestMapping(value="/")
    public String welcomeUser(Map<String,String> model) {
        model.put("message", pass);
        return "index";
    }
}

我的index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>ThymLeaf Demo</title>
<link rel="stylesheet" th:href="@{/main.css}" href="../../main.css">
</head>
<body>
    <div class="container">
        <h1>Spring Boot Using ThymLeaf</h1>
        <h2>
            <span th:if="${message != null}"
                th:text="'Message:' + ${message}">> 
            </span>
        </h2>
    </div>
</body>
</html>


它显示 Spring Boot Using ThymLeaf 而不是 message 属性,因为它带有一个空值,但为什么?

【问题讨论】:

  • 但它是 EL 我怎么能错过 $ 而问题是它带有一个 null 这就是为什么它没有显示 Message:
  • 当您将参数指定为 Map 模型时,我不知道传递给您的函数的是什么,但您通常使用 Model、ModelMap 或 ModelAndView。有了这些,这段代码应该可以工作。你有什么理由使用 Map
  • @espendennis 这也是有效的 Spring 代码,对 html-tempates(Thymleaf、jsp、EL 等)没有影响。
  • 是的,问题出在 ${ message } 它没有读取模型属性中的数据,这是我们在 thymleaf 中访问模型数据的方式
  • 在浏览器中查看源代码并确保它实际上将文件解释为 Thymeleaf。

标签: spring thymeleaf


【解决方案1】:

你可以检查这个答案

<span th:if="${message} != null">
  <span th:text= "'Message:' + ${message}"></span>
</span>

【讨论】:

    【解决方案2】:

    您的非空检查在这里不正确,请执行以下操作:--

    <span th:if="${message} != null or ${message} !=  '' ">
      <span th:text= "${message}"></span>
    </span>
    


    PS:- 确保您正确放置逗号,否则您的页面将出现错误。

    【讨论】:

    • 不,问题是 ${message} 它无法访问模型属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2019-11-27
    • 2019-03-23
    • 1970-01-01
    • 2011-08-04
    • 2011-06-10
    相关资源
    最近更新 更多