PS:禁止拷贝形式转载,转载请以URL形式
1.参考
参考文章:# SpringMVC自定义兼容性HandlerMapping
2.简介
实现对静态资源路径的动态修改,达到控制前端资源切换的效果。
有两种实现方式
. A:基于自定义兼容性HandlerMapping
. B:更新原有映射
3.环境
- jdk11
- springboot:2.2.8.RELEASE
4.代码
4.1 基于自定义兼容性HandlerMapping
参考文章:# SpringMVC自定义兼容性HandlerMapping
4.2 更新原有映射
原理
WebMvcConfigurationSupport 注册 各个类型的HandlerMapping
其中注册的 resourceHandlerMapping 负责映射静态资源
通过修改其原有的映射信息达到控制更新
默认映射
@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);
}
}
}