Spring Boot运行HTML需区分静态与动态页面:静态文件放src/main/resources/static目录,直接访问路径即可;动态页面需引入Thymeleaf依赖,HTML文件置于templates目录,通过@Controller映射路径返回模板名,结合Spring Boot内嵌服务器访问。配置正确后,默认启动8080端口,可自定义端口于application.properties。结构清晰,静态用static,动态配Controller+templates。

Spring Boot 运行 HTML 文件并不像直接双击打开那样简单,因为它是一个后端框架,需要通过内嵌的 Web 服务器(如 Tomcat)来提供静态资源或结合模板引擎渲染页面。以下是具体步骤,帮助你在 Spring Boot 项目中成功运行 HTML 文件。
1. 将 HTML 文件放在正确的位置
Spring Boot 默认会从 src/main/resources/static 目录下提供静态资源文件(包括 HTML、CSS、JS 等)。如果你只是想访问一个简单的 HTML 页面,比如 index.html,只需:
- 在 src/main/resources/ 下创建 static 文件夹(如果不存在)
- 将你的 HTML 文件放入该目录,例如:src/main/resources/static/hello.html
完成后,启动项目,访问 http://localhost:8080/hello.html 即可看到页面内容。
2. 使用模板引擎渲染 HTML(推荐用于动态页面)
如果 HTML 页面需要与后端数据交互(如显示用户信息),建议使用模板引擎,如 Thymeleaf。
立即学习“前端免费学习笔记(深入)”;
- 添加 Thymeleaf 依赖到 pom.xml:
- 将 HTML 文件放在 src/main/resources/templates 目录下(如:hello.html)
- 创建一个 Controller 映射路径:
public class PageController {
@GetMapping("/hello")
public String showHello() {
return "hello"; // 返回模板名,不带 .html
}
}
访问 http://localhost:8080/hello,Spring Boot 会自动渲染 templates 目录下的 hello.html 页面。
3. 启动并访问应用
确保你的主类上有 @SpringBootApplication 注解,并运行 main 方法启动服务。
@SpringBootApplicationpublic class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
服务默认运行在 8080 端口,根据你的配置访问对应 URL 即可。
4. 注意事项
- 静态 HTML 放 static,动态模板放 templates
- Thymeleaf 模板默认以 .html 结尾,无需额外配置
- 可以自定义端口,在 application.properties 中设置:
server.port=9090 - 支持其他模板引擎如 FreeMarker、Velocity,但 Thymeleaf 是最常用的
基本上就这些。只要文件位置对、路径映射正确,Spring Boot 运行 HTML 很简单。静态页走 static,动态页配 Controller + templates,结构清晰又高效。










