Springboot動(dòng)態(tài)修改資源映射路徑

PS:禁止拷貝形式轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)以URL形式

1.參考

參考文章:# SpringMVC自定義兼容性HandlerMapping

2.簡(jiǎn)介

實(shí)現(xiàn)對(duì)靜態(tài)資源路徑的動(dòng)態(tài)修改,達(dá)到控制前端資源切換的效果。
有兩種實(shí)現(xiàn)方式
. A:基于自定義兼容性HandlerMapping
. B:更新原有映射

3.環(huán)境

  1. jdk11
  2. springboot:2.2.8.RELEASE

4.代碼

4.1 基于自定義兼容性HandlerMapping

參考文章:# SpringMVC自定義兼容性HandlerMapping

4.2 更新原有映射

原理

  1. WebMvcConfigurationSupport 注冊(cè) 各個(gè)類型的HandlerMapping

  2. 其中注冊(cè)的 resourceHandlerMapping 負(fù)責(zé)映射靜態(tài)資源

  3. 通過修改其原有的映射信息達(dá)到控制更新

image.png

默認(rèn)映射

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String req = "/html/**";
        String path = "file:C:/html/";
        registry.addResourceHandler(req).addResourceLocations(path);
    }

}

修改映射

    public static void main(String[] args) throws Exception {
        ApplicationContext app = SpringApplication.run(App.class, args);
        update(app,"/html/**","file:D:/html/");
    }

    public static void update(ApplicationContext ctx, String url, String resource) {
        SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) ctx.getBean("resourceHandlerMapping");
        ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) mapping.getUrlMap().get(url);
        if (handler != null) {
            handler.setLocationValues(List.of(resource));
            handler.getLocations().clear();
            handler.getResourceResolvers().clear();
            try {
                handler.afterPropertiesSet();
            } catch (Throwable ex) {
                throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
            }
        }
    }


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容