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

如何在Spring Boot中不使用Thymeleaf返回HTML页面

问题解析与解决方案

当你移除spring-boot-starter-thymeleaf依赖后,Spring Boot失去了模板视图解析器,无法将你返回的视图名(如index)解析为对应的HTML页面,这就是核心问题。你尝试的几种方法无效的原因如下:

  • 添加@ResponseBody或改用@RestController:这两个注解的作用是直接返回字符串/JSON数据,跳过视图渲染流程,自然不会返回HTML页面
  • 使用ModelAndView:没有模板引擎时,Spring无法将viewName映射到实际的HTML文件,所以无论设置什么名称都无效

针对这个问题,有两种常见解决思路:

思路1:替换为其他模板引擎

如果你只是不想用Thymeleaf,可以换成其他支持的模板引擎,比如FreeMarker:

  1. 在pom.xml中添加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  1. 将HTML文件(FreeMarker支持直接使用.html格式)放在src/main/resources/templates/目录下
  2. 保持@Controller注解,直接返回视图名即可:
@GetMapping("/")
public String index() {
    return "index"; // 对应templates/index.html
}

思路2:直接返回静态HTML文件

如果不需要模板渲染,只想返回静态HTML,只需将文件放在Spring Boot默认的静态资源目录:

  1. 将index.html放在src/main/resources/static/目录下(或public/、resources/目录)
  2. 此时有两种访问方式:
    • 直接通过URL访问:比如http://localhost:8080/index.html,Spring Boot会自动映射静态资源
    • 或者通过@Controller方法跳转(无需模板引擎):
      @GetMapping("/")
      public String index() {
          return "forward:/index.html";
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:04:55