在Spring boot项目中,整合Thymeleaf模板引擎,在html文件中使用th:text="${msg}"属性标签时,提示报错“无法解析msg”。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>This is Thymeleaf</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>

对应的Controller代码如下:

@Controller
public class ThymeleafController {
    @GetMapping("/home")
    public String test1(Model model){
        model.addAttribute("msg", "Welcome to home page! Enjoy yourself,please!");
        return "home";
    }
}  

原因分析:

在使用Model来设置变量值时,若返回类型为String,则页面无法获取到该变量。

解决方案:

将方法的返回类型修改为Object类型。则页面可以正常解析Model实例中的变量值。

@Controller
public class ThymeleafController {
    @GetMapping("/home")
    public Object test1(Model model){
        model.addAttribute("msg", "Welcome to home page! Enjoy yourself,please!");
        return "home";
    }
}

页面可以正常获取到${msg}变量的值。

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐