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

Thymeleaf从Controller传值至View显示null问题求助

问题解决方法

1. 修正Thymeleaf命名空间

你的HTML文件中Thymeleaf命名空间配置错误,这会导致框架无法正确识别并解析th:text属性。将html标签的xmlns:th属性替换为正确的Thymeleaf命名空间:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
<h1 th:text="'Hello ' + ${mensaje} + '!'"></h1>
</body>
</html>

(注:在"Hello"后添加空格,让最终输出格式更符合预期)

2. 确保Controller被Spring Boot扫描

Spring Boot默认只会扫描主启动类所在包及其子包下的组件。检查你的目录结构:

  • 如果主启动类位于src/main/java/com/example/Application.java,那么HelloController应放在com/example/controller包下,而非单独的controller包。
  • 若不想调整包结构,可在主启动类上添加@ComponentScan注解指定扫描范围:
@SpringBootApplication
@ComponentScan(basePackages = {"controller"})
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

3. 优化变量传递方式

避免使用类成员变量传递值,直接在方法内赋值更稳妥,能避免初始化相关问题:

@Controller
public class HelloController {
    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("mensaje", "Springboot");
        return "index";
    }
}

完成以上修改后重启应用,访问/即可看到预期的"Hello Springboot!"。

内容的提问来源于stack exchange,提问作者Ignacio A.S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:42:11