SpringBoot Web开发、导入静态资源

99 阅读1分钟

思考:SpringBoot配置内容?能否修改?能修改哪些?能不能拓展?

  • xxxAutoConfiguration: 向容器中自动配置组件
  • xxxProperties: 自动配置类,装配配置文件中自定义的一些内容

要解决的问题:

  • 导入静态资源
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配拓展SpringMVC
  • 增删改查
  • 拦截器
  • 国际化

创建springboot项目

image.png

image.png

静态资源

源码WebMvcAutoConfiguration

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (this.servletContext != null) {
                ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                registration.addResourceLocations(new Resource[]{resource});
            }

        });
    }
}

webjars ?

添加webjars jquery依赖

<!--webjars jQuery-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

访问测试

刷新Maven,访问url localhost:8080/webjars/jquery/3.4.1/jquery.js image.png

静态资源目录和配置

@ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false)
public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATTONS = { "classpath:/NETA-INF/resources/","classpath:/resources/","classpath:/static/" , "classpath:/public/"
};

创建目录测试

image.png

image.png

静态资源优先级

resources > static > public

总结

  • 在SpringBoot中,可以通过使用以下方式处理静态资源

    • webjars localhost:8080/webjars/
    • public static /** resources localhost:8080/
  • 优先级: resources > static(默认) > public