✅P136_商城业务-首页-整合thymeleaf渲染首页

gong_yz大约 1 分钟谷粒商城

引入thymeleaf依赖

cfmall-product服务中导入thymeleaf依赖

cfmall-product/pom.xml

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

application.yml

关闭页面缓存,以便在生产环境下可以实时看到数据变化

cfmall-product/src/main/resources/application.yml

spring:
  //省略......
  thymeleaf:
    cache: false  #关闭页面缓存

导入index静态资源

将首页资源中的index文件夹复制到static文件夹下,将index.html复制到templates文件夹下


访问静态资源

url:http://localhost:8200/index/css/GL.cssopen in new window


访问首页

url:http://localhost:8081/open in new window

SpringBoot自动配置,将默认访问index.html


自动加载资源原理

org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.EnableWebMvcConfiguration#welcomePageHandlerMapping

        @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new 				     TemplateAvailabilityProviders(applicationContext), 
            	applicationContext, 
            	this.getWelcomePage(), //2
            	this.mvcProperties.getStaticPathPattern());  //1
            	welcomePageHandlerMapping.setInterceptors(this.getInterceptors());
            	return welcomePageHandlerMapping;
        }

1、org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties#getStaticPathPattern

    public String getStaticPathPattern() {
        return this.staticPathPattern;
    }

org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties

private String staticPathPattern;

    public WebMvcProperties() {
        this.staticPathPattern = "/**";
        //省略其它代码
    }

2、org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.EnableWebMvcConfiguration#getWelcomePage

        private Optional<Resource> getWelcomePage() {
            String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

org.springframework.boot.autoconfigure.web.ResourceProperties#getStaticLocations

    public String[] getStaticLocations() {
        return this.staticLocations;
    }

org.springframework.boot.autoconfigure.web.ResourceProperties

private String[] staticLocations;

public ResourceProperties() {
   this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
   //省略其它代码
}

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

所有访问/**的路径都会去类路径下的 /META-INF/resources//resources//static//public/ 下查找资源