Springboot动态注册静态资源目录

148次阅读
没有评论

Springboot 动态注册静态资源目录

https://blog.csdn.net/lqzkcx3/article/details/122641111

Springboot 可以在 application 配置文件中设置静态资源文件,如果你想要动态注册静态资源目录,看看这里。

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;

@Api
@RestController
@RequestMapping("dynamicStatic")
public class StaticResourceDynamicRegistryController {
    @Autowired
    private ApplicationContext applicationContext;

    @ApiOperation(value = "registry")
    @PostMapping(value = "registry", produces = MediaType.APPLICATION_JSON_VALUE)
    public String registry(@ApiParam(defaultValue="/fulizhe") @RequestParam String resourceHandler, //
            @ApiParam(defaultValue="E:/data/") @RequestParam String resourceLocations) {registerHandlersForAdditionalStatisResource(Collections.singletonMap(resourceHandler, resourceLocations));

        return "SUCCESS";
    }

    private void registerHandlersForAdditionalStatisResource(Map<String, String> registerMapping) {
        // 这些值的由来参见: 
        final UrlPathHelper mvcUrlPathHelper = applicationContext.getBean("mvcUrlPathHelper", UrlPathHelper.class);
        final ContentNegotiationManager mvcContentNegotiationManager = applicationContext
                .getBean("mvcContentNegotiationManager", ContentNegotiationManager.class);
        final ServletContext servletContext = applicationContext.getBean(ServletContext.class);
        // SimpleUrlHandlerMapping.java
        final HandlerMapping resourceHandlerMapping = applicationContext.getBean("resourceHandlerMapping",
                HandlerMapping.class);

        // 这里存放的是 springmvc 已经建立好的映射处理
        @SuppressWarnings("unchecked")
        final Map<String, Object> handlerMap = (Map<String, Object>) ReflectUtil.getFieldValue(resourceHandlerMapping,
                "handlerMap");

        final ResourceHandlerRegistry resourceHandlerRegistry = new ResourceHandlerRegistry(applicationContext,
                servletContext, mvcContentNegotiationManager, mvcUrlPathHelper);

        for (Map.Entry<String, String> entry : registerMapping.entrySet()) {String urlPath = entry.getKey();
            String resourceLocations = entry.getValue();
            final String urlPathDealed = StrUtil.appendIfMissing(urlPath, "/**");
            final String resourceLocationsDealed = StrUtil.appendIfMissing(resourceLocations, "/");

            // 先移除之前自定义注册过的...
            handlerMap.remove(urlPathDealed);
            // 重新注册
            resourceHandlerRegistry.addResourceHandler(urlPathDealed)
                    .addResourceLocations("file:" + resourceLocationsDealed);
        }

        final Map<String, ?> additionalUrlMap = ReflectUtil
                .<SimpleUrlHandlerMapping>invoke(resourceHandlerRegistry, "getHandlerMapping").getUrlMap();

        ReflectUtil.<Void>invoke(resourceHandlerMapping, "registerHandlers", additionalUrlMap);
    }
}
 0
评论(没有评论)
验证码