zoukankan      html  css  js  c++  java
  • Springboot访问静态资源

    Springboot访问静态资源

    参考

    SpringBoot静态资源的访问

    默认的静态资源位置

    classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/

    @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
    public class ResourceProperties {
    
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
            "classpath:/META-INF/resources/",                              
            "classpath:/resources/", 
            "classpath:/static/", 
            "classpath:/public/" };
    
        public void setStaticLocations(String[] staticLocations) {
            this.staticLocations = appendSlashIfNecessary(staticLocations);
        }
    
        private String[] appendSlashIfNecessary(String[] staticLocations) {
            String[] normalized = new String[staticLocations.length];
            for (int i = 0; i < staticLocations.length; i++) {
                String location = staticLocations[i];
                normalized[i] = location.endsWith("/") ? location : location + "/";
            }
            return normalized;
        }
    
    }
    

    自定义静态资源位置

    方法一:配置文件 spring.resources.static-locations

    # windows中2种斜杠都可以,Linux中使用右斜杠。统一使用右斜杠。
    spring:
      resources:
        #static-locations: classpath:/mybatis/, file:E:imageaccountimg
        static-locations: classpath:/mybatis/, file:E:${server.servlet.context-path}/image/account/img
    

    方法二:实现WebMvcConfigurer接口

    package com.mozq.boot.upload01.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        /*
        	注意:结尾一定以斜杠结尾,不然不起效果。
        */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**")
                .addResourceLocations("file:E:\mozq\image\account\img\",
                        "classpath:/static/",
                        "file:e:/mozq/");
        }
    }
    

    静态资源访问路径匹配

    # 指定以.txt结尾的url是访问静态资源。
    spring:
      mvc:
        static-path-pattern: /**/*.txt
    
    @ConfigurationProperties(prefix = "spring.mvc")
    public class WebMvcProperties {
        private String staticPathPattern = "/**";
    }
    
  • 相关阅读:
    identityser4 samesit 问题
    mysql 8 root密码重置
    OutSystems学习笔记。
    获取两个List中的不同元素,4种方法,逐步优化,学习使用
    java 配置在.properties文件中的常量
    java POST 传值 加签 验证
    springboot jpa 多条件查询(多表)
    java代码行数统计工具类
    Map集合遍历的4种方法
    springboot jpa 多条件查询(单表)
  • 原文地址:https://www.cnblogs.com/mozq/p/11877618.html
Copyright © 2011-2022 走看看