静态资源导入
WebMvcAutoConfiguration.java
- webjars不推荐
WebMvcAutoConfiguraion => EnableWebMvcConfiguraion => addResourceHandler
去classpath:/META-INF/resources/webjars/ 找对应的资源)
- spring.mvc.staticPathPattern> Resources.staticLocations > static(默认) > public
- @Override addResourceHandler
```java
public class WebMvcAutoConfiguration {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
} }if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");return;}addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");// staticPathPattern, staticLocationsaddResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (this.servletContext != null) {ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);registration.addResourceLocations(resource);}});
public static class Resources {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/"};// ...
}
```javapublic class MyWebMvcConfigurer implements WebMvcConfigurer {// addResourceHandler、addResourceLocations配置静态资源映射// 注意addResourceLocations的路径末尾必须有/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/file/**").addResourceLocations("file:/home/admin/picture/");}}
首页
private Optional<Resource> getWelcomePage() {String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();}// 欢迎页就是一个location下的的 index.html 而已private Resource getIndexHtml(String location) {return this.resourceLoader.getResource(location + "index.html");}
Thymeleaf
ThymeleafAutoconfiguration
不是重点,见idea tutorial和视频笔记
问题
地址栏必须输入.html后缀才能访问,例如
[http://localhost:8080/login.html](http://localhost:8080/login.html)可以,[http://localhost:8080/login](http://localhost:8080/login.html)不可以,除非配置addViewController。@Configurationpublic class MyMvcConfig implements WebMvcConfigurer {/*** 替代默认的index首页*/@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("index");registry.addViewController("/index.html").setViewName("index");registry.addViewController("/main.html").setViewName("dashboard");}}
