web开发的入门就是helloworld案例。
添加静态资源
静态资源比如js等,可以从 https://www.webjars.org/ 查询webjars的maven依赖导入。
可以看到,静态资源是存放在resources/webjars/目录下, 我们在哪里存放自己的静态资源呢?在自动配置jar中找到
ResourceProperties 类,该类中存在定义:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
};
springboot会在classpath下的/static
(or /public
or /resources
or /META-INF/resources
) 目录中查找静态资源,或者来自我们自定义的ServletContext中。自定义的配置类需要实现WebMvcConfigurer接口并覆写addResourceHandlers方法。
默认情况下映射资源/**,我们可以配置spring.mvc.static-path-pattern
属性对其进行调整
默认访问静态资源目录下的index.html页面。
图表默认加载静态资源目录下的**/favicon.ico
如何自定义静态资源路径?
添加配置spring.resources.static-location=...,...
模板引擎
SpringBoot不推荐使用JSP作为模板引擎而推荐thymleaf。
thymleaf依赖启动器:spring-boot-starter-thymeleaf 。
如何使用thymeleaf?首先引入thymeleaf的启动器:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
启动器的默认版本为2.1.6,在properties标签中修改thymeleaf版本:
<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
layout和thymeleaf的版本相差一个。
如何使用thymeleaf?
查看自动配置的源码可以看到:
thymeleaf访问resources/templates/下的所有html页面。
<html xmlns:th="http://www.thymeleaf.org">
thymeleaf语法规则
th:(任意html属性)="${...}" 替换html原来属性,方便前后端分离开发。
表达式:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}