SpringBoot2.x入门到项目实战课程系列(第五章)( 三 )

  • 总结:
  • 当接受到 /** 请求访问资源时, 会被映射到下面4个类路径下的静态资源目录中查找
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
  • 访问 localhost:8080/style.css 会在上面四个静态资源路径 中查找文件
5.2.3 欢迎页映射
  • 在 WebMvcAuotConfiguration.welcomePageHandlerMapping() 分析 欢迎页映射
@Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) { return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext=======查找欢迎页========, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());}
  • getWelcomePage() 方法获取 欢迎页面 可存储路径
private Optional getWelcomePage() { String[] locations = ===2. 上面说的4个静态资源路径加上 "/" 路径 getResourceLocations( =====1. 获取上面说的4个静态资源路径 this.resourceProperties.getStaticLocations()); ==================================在上面路径下查找 index.html 页面 return Arrays.stream(locations).map(this::getIndexHtml). filter(this::isReadable).findFirst();}// 上面获取的路径中查找 index.html 页面private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html");}
  • 分析后, 会从 4个静态资源目录 + 根路径 / 中 查找 index.html 页面
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public//: 当前项目根路径下
  • 会在 静态资源目录下 与 根路径查找 (按该顺序) index.html页面; 收到 “/**” 请求映射
  • 访问 localhost:8080/ 会在上面5个目录中查找 index.html 页面(因为/也属于 /** )
5.2.4 图标映射
  • Spring Boot 会在静态资源目录下 与 根路径(按该顺序) 查找 faicon.ico 页面;
  • 如果存在这样的文件 , Spring Boot 会自动将其设置为应用图标 。
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public//: 当前项目根路径下5.3 Thymeleaf 模板引擎Spring Boot 官方不推荐使用JSP , 因为内嵌的 Tomcat 、Jetty 容器不支持以 jar 形式运行 JSP 。 Spring Boot中提供了大量模板引擎 , 包含 Freemarker、Mastache、Thymeleaf 等 。而 Spring Boot 官方推荐使用Thymeleaf 作为模板引擎 ,因为 Thymeleaf 提供了完美的 SpringMVC 的支持 。
SpringBoot2.x入门到项目实战课程系列(第五章)文章插图
5.3.1 引入 Thymeleaf
  • pom.xml 加入 Thymeleaf 启动器
org.springframework.boot spring-boot-starter-thymeleaf5.3.2 使用 Thymeleaf
  • 模板文件放在哪里 ?
@ConfigurationProperties( prefix = "spring.thymeleaf" )public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING; public static final String DEFAULT_PREFIX = "classpath:/classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";