You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf无法识别Model属性,页面无法渲染参数值问题排查

问题排查与解决

你的问题核心是视图解析器配置错误,同时Thymeleaf的命名空间也有误,导致Model中的属性无法被Thymeleaf视图渲染。以下是具体修复步骤:

1. 替换错误的视图解析器

你当前配置的InternalResourceViewResolver是Spring用于解析JSP视图的组件,完全不兼容Thymeleaf。需要替换为Thymeleaf专属的视图解析器配置:

修改SpringConfig类:

@Configuration
@ComponentScan("com.nosferat.springapp")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    // 配置Thymeleaf模板解析器
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }

    // 配置Thymeleaf模板引擎
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    // 配置Thymeleaf视图解析器
    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

2. 修正Thymeleaf命名空间

你的HTML视图中Thymeleaf的命名空间写错了,正确的命名空间是http://www.thymeleaf.org,不是xhtml的地址。修改hello.html的根标签:

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    <p th:text="${message}"></p>
</body>
</html>

3. 确保依赖正确引入

如果是Maven项目,需要在pom.xml中添加Thymeleaf与Spring整合的依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.1.2.RELEASE</version> <!-- 使用对应Spring版本的兼容版本 -->
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.20</version> <!-- 你的Spring Core版本 -->
</dependency>

完成以上修改后,重新启动项目访问http://localhost:8080/hello?name=Tom,页面就能正确渲染出message属性的值了。

内容的提问来源于stack exchange,提问作者Nosferatzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:48:29