• springboot自定义静态文件目录,解决jar打包后修改页面等静态文件的问题


    1.问题

    springboot开发时候,一般将文件放在resources目录,但是发布后想修订文件或是开发时候修改了文件内容一般需重新打包或者重启动才能达到效果;

    2.原因

    将资源文件打包入jar包,访问的是编译的结果,所以运行后访问的不是源码目录中的文件。致使修改效果要重新编译才能生效。一般可以妥协采用自定编译来解决,但是仍然有发布后无法修改资源的困扰。

    3.解决

    使用springboot重新定义静态资源的目录,达到访问jar包外部目录的效果,加上user.dir的使用,可以让jar包访问运行jar包的当前目录中的指定目录的静态文件。主要使用springboot的拦截器方法。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class clientConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry){
            registry.addResourceHandler("/res/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/res/");
    //        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        }
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")//设置允许跨域的路径
                    .allowedOrigins("*")//设置允许跨域请求的域名
                    .allowCredentials(true)//是否允许证书 不再默认开启
                    .allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
                    .maxAge(3600);//跨域允许时间
        }
    }
    
  • 相关阅读:
    「考试总结」2020-12-01 入冬
    「考试总结」2020-11-30 低智
    2020-11-29 自闭瞎写
    「晚测反思」2020-11-26 点亮
    「晚测反思」2020-11-28 复盘
    「刷题笔记」二分图匹配
    「刷题笔记」AC自动机
    「刷题笔记」哈希,kmp,trie
    「刷题笔记」数学I
    「刷题笔记」DP优化-斜率优化
  • 原文地址:https://www.cnblogs.com/pcode/p/9202031.html
Copyright © 2020-2023  润新知