美文网首页
springboot WebMvcConfigurer配置静态资

springboot WebMvcConfigurer配置静态资

作者: 定格r | 来源:发表于2020-02-29 18:25 被阅读0次

    一、springboot 默认静态文件路径

    Spring Boot 默认为我们提供了静态资源处理,默认提供的静态资源映射如下:

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

    这些目录的静态资源时可以直接访问到的。上面这几个都是静态资源的映射路径,优先级顺序为:META-INF/resources > resources > static > public

    二、自定义配置静态资源配置

    package com.example.materials.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 FileConfig implements WebMvcConfigurer {
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/**")
                     .addResourceLocations("classpath:/META-INF/resources/")
                     .addResourceLocations("file:E:/weixin/");
     }
    }
    

    将资源路径定向到 materials 文件路径下。
    注意:这里需要注意的是,配置外部的资源要使用file声明,比如磁盘上的静态资源,配置jar包内部的使用classpath声明。

    3、WebMvcConfigurer接口解决跨域问题

    跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。

    所谓同源是指,域名,协议,端口均相同.
    浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。

    解决办法:

    只需写如下配置文件即可解决。

    package com.example.materials.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * 跨域问题处理
     */
    @Configuration
    public class Cors extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                    .allowCredentials(true).maxAge(3600);
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:springboot WebMvcConfigurer配置静态资

          本文链接:https://www.haomeiwen.com/subject/pkdmhhtx.html