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

Spring Controller中@GetMapping无法正确跳转HTML页面——module-info.java引发模板解析错误的解决方法

Spring Controller中@GetMapping无法正确跳转HTML页面——module-info.java引发模板解析错误的解决方法

嘿,我之前也碰到过Java模块系统(JPMS)下Spring Boot资源访问的坑,你的问题核心是添加module-info.java后,Thymeleaf模块无法读取到你项目里的模板资源,咱们一步步来解决:

问题根源

在Java模块系统中,模块内部的资源默认是封闭状态的,其他模块(比如处理模板的thymeleaf.spring5)没有权限访问你模块里templates目录下的文件。这就是为什么没加module-info时一切正常,加了之后就抛出Error resolving template [main]异常的原因。

解决方案:在module-info.java中开放资源路径

你需要在module-info.java里显式声明开放templates和static目录下的资源,让Thymeleaf和Spring Web模块能读取到它们。修改你的module-info.java,添加以下内容:

module sswwy {
    // 保留你原有的exports、opens、requires语句不变
    
    // 开放templates目录给Thymeleaf Spring5模块和Spring WebMVC模块,用于模板解析
    opens templates to thymeleaf.spring5, spring.webmvc;
    // 开放static目录给Spring Web模块,用于静态资源访问
    opens static to spring.web;
}

为什么要这么做?

  • opens templates to ...:允许指定的模块(这里是负责模板处理的thymeleaf.spring5和Spring MVC核心的spring.webmvc)访问你模块里templates目录下的所有资源,这样Thymeleaf才能找到并解析main.html。
  • opens static to ...:确保Spring Web能读取到静态资源(比如你的index.html),虽然这不是当前报错的直接原因,但一起配置能避免后续静态资源访问的问题。

如果不想精准指定模块,也可以用opens templates;(开放给所有模块),不过精准开放更符合模块系统的封装原则,安全性更高。

验证步骤

  1. 保存修改后的module-info.java
  2. 重启Spring Boot应用
  3. 再次访问http://127.0.0.1:8080/p1,应该就能正常加载main.html了!

额外提示

你在debug中看到的return null;,本质就是Thymeleaf的模板解析器无法访问到main.html资源,所以返回null导致抛出模板找不到的异常,开放资源路径后这个问题就会消失。

备注:内容来源于stack exchange,提问作者Nor.Z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 15:53:12