静态资源导入

WebMvcAutoConfiguration.java

  1. webjars不推荐

WebMvcAutoConfiguraion => EnableWebMvcConfiguraion => addResourceHandler
去classpath:/META-INF/resources/webjars/ 找对应的资源)

  1. spring.mvc.staticPathPattern> Resources.staticLocations > static(默认) > public
  2. @Override addResourceHandler ```java public class WebMvcAutoConfiguration { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
    1. if (!this.resourceProperties.isAddMappings()) {
    2. logger.debug("Default resource handling disabled");
    3. return;
    4. }
    5. addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
    6. // staticPathPattern, staticLocations
    7. addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
    8. registration.addResourceLocations(this.resourceProperties.getStaticLocations());
    9. if (this.servletContext != null) {
    10. ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
    11. registration.addResourceLocations(resource);
    12. }
    13. });
    } }

public static class Resources {

  1. private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
  2. "classpath:/META-INF/resources/",
  3. "classpath:/resources/",
  4. "classpath:/static/",
  5. "classpath:/public/"
  6. };
  7. // ...

}

  1. ```java
  2. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  3. // addResourceHandler、addResourceLocations配置静态资源映射
  4. // 注意addResourceLocations的路径末尾必须有/
  5. @Override
  6. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  7. registry
  8. .addResourceHandler("/file/**")
  9. .addResourceLocations("file:/home/admin/picture/");
  10. }
  11. }

image.png

首页

  1. private Optional<Resource> getWelcomePage() {
  2. String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
  3. return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
  4. }
  5. // 欢迎页就是一个location下的的 index.html 而已
  6. private Resource getIndexHtml(String location) {
  7. return this.resourceLoader.getResource(location + "index.html");
  8. }

Thymeleaf

ThymeleafAutoconfiguration
不是重点,见idea tutorial和视频笔记

问题

  1. 地址栏必须输入.html后缀才能访问,例如[http://localhost:8080/login.html](http://localhost:8080/login.html)可以,[http://localhost:8080/login](http://localhost:8080/login.html)不可以,除非配置addViewController。

    1. @Configuration
    2. public class MyMvcConfig implements WebMvcConfigurer {
    3. /**
    4. * 替代默认的index首页
    5. */
    6. @Override
    7. public void addViewControllers(ViewControllerRegistry registry) {
    8. registry.addViewController("/").setViewName("index");
    9. registry.addViewController("/index.html").setViewName("index");
    10. registry.addViewController("/main.html").setViewName("dashboard");
    11. }
    12. }