SpringBoot学习笔记02
发布日期:2021-05-08 03:02:37 浏览次数:27 分类:精选文章

本文共 1492 字,大约阅读时间需要 4 分钟。

Spring Boot Web 开发指南

1. 静态资源映射

在 Spring Boot 应用中,静态资源(如 HTML、CSS、JavaScript、 favicon.ico 等)通常会被映射到以下四个类路径目录中查找:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

当客户端请求访问这些资源时,框架会自动查找上述路径下的文件。


2. Thymeleaf 模板引擎

Spring Boot 不推荐使用 JSP,因其内置的 Tomcat、Jetty 容器不支持以 jar 形式运行 JSP。相反,Spring Boot 建议使用 Thymeleaf 作为模板引擎,因为它提供了完美的 Spring MVC 支持。

2.1 引入 Thymeleaf

在项目的 pom.xml 中添加 Thymeleaf 依赖:

org.springframework.boot
spring-boot-starter-thymeleaf

2.2 模板文件存放位置

将 HTML 页面放到 classpath:/templates/ 目录下,Thymeleaf 引擎会自动渲染这些模板。

2.3 Thymeleaf 命名空间

在 HTML 页面开头加入 Thymeleaf 命名空间:

2.4 Thymeleaf 语法示例

    
Spring Boot

这里显示名字


3. Spring Boot 热部署

在开发过程中,希望能够无需重启应用即可看到修改效果。以下是实现热部署的方法:

3.1 禁用模板缓存

在开发环境中关闭 Thymeleaf 模板缓存:

spring.thymeleaf.cache=false

3.2 添加热部署依赖

添加 Spring Boot Devtools 依赖:

org.springframework.boot
spring-boot-devtools

3.3 IDE 配置

在 IntelliJ IDEA 中,确保项目设置为自动编译:

  • 按下 Ctrl + F9 或者选择菜单栏中的 Build - Project
  • 也可以在 File - Settings - Build, Execution, Deployment - Compiler 中勾选 Build project automatically

4. 扩展 Spring MVC 功能

如果需要保留 Spring Boot 的默认特性,同时扩展新的功能,可以创建自定义的 WebMvcConfigurer 类并添加配置:

@Configurationpublic class MySpringMvcConfigurer implements WebMvcConfigurer {    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/korbin").setViewName("hello");    }}

通过以上方法,你可以更高效地进行 Spring Boot Web 开发,实现热部署并扩展应用功能。

上一篇:lamdba03 Java8新特性之四:Stream API
下一篇:Spring Boot学习笔记01

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年05月11日 13时31分52秒