• Springboot:静态资源映射方式


    一、webjars方式映射静态资源文件

    SpringBoot默认的打包方式是jar(Java归档),那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的

    我们先来看一下这个静态资源映射规则,SpringBoot中,SpringMVC的web配置都在org.springframework.boot.autoconfigure.web.servlet包下的WebMvcAutoConfiguration 这个配置里面,我们找到addResourceHandlers这个方法,该方法用于处理webjars方式的静态资源映射

    addResourceHandlers源码

    1. @Override
    2. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    3. super.addResourceHandlers(registry);
    4. if (!this.resourceProperties.isAddMappings()) {
    5. logger.debug("Default resource handling disabled");
    6. return;
    7. }
    8. ServletContext servletContext = getServletContext();
    9. addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
    10. addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
    11. registration.addResourceLocations(this.resourceProperties.getStaticLocations());
    12. if (servletContext != null) {
    13. registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
    14. }
    15. });
    16. }

    阅读一下源码,所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源,那什么是webjars呢?

    webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。使用SpringBoot可以使用webjars,官网:WebJars - Web Libraries in Jars

    只需导入相应pom依赖即可使用

     二、自定义WebMvcAutoConfiguration

    自定义一个WebMvcConfig继承WebMvcConfigurationSupport 

    1. @Configuration
    2. public class WebMvcConfig extends WebMvcConfigurationSupport {
    3. /**
    4. * 添加静态资源映射
    5. * @param registry
    6. */
    7. @Override
    8. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    9. // "/backend/**" 表示/backend下的所有文件夹及其子文件夹
    10. registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
    11. registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    12. }
    13. }

    输入http://localhost:8080/backend/index.html即可访问

    三、在application.properties中手动配置静态资源访问路径

    1. # 自定义静态资源访问路径,可以指定多个,之间用逗号隔开
    2. spring.resources.static-locations=classpath:/myabc/,classpath:/myhhh

    正如上面注释所描述的一样,自定义静态资源访问路径,可以指定多个,之间用逗号隔开,其中使用这种方式特别要注意:自定义静态资源后,SpringBoot默认的静态资源路径将不再起作用

  • 相关阅读:
    Leetcode416. 分割等和子集
    MySQL根据备注查询表、字段
    【IDEA】idea2021.2.1版本无限试用30天重置脚本 实战教程
    ArduinoIDE快速搭建ESP32开发环境
    pycharm访问远程GPU服务器终端并使用Tmux终端复用器
    Jenkins pipeline 自动部署实践
    知识头条-大脑
    分享一个用python写的本地WIFI密码查看器
    智能合约平台开发指南
    AR打卡小程序:构建智能办公的新可能
  • 原文地址:https://blog.csdn.net/m0_63748493/article/details/126595833