springboot加载static下的静态资源

在yml中配置:
spring:
resources:
static-locations: classpath:/static
或者在properties中配置:spring.resources.static-locations=classpath:/static

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 静态资源默认是放在 `/static`,`/public`,`/resources`,`/META-INF/resources` 目录下的,这些资源在应用启动时会被加载到内存供访问。如果需要动态加载静态资源,可以使用 `ResourceHttpRequestHandler`。 下面是一个简单示例: 1. 创建 `DynamicResourceController` 控制器类,该类负责动态加载静态资源: ```java @Controller public class DynamicResourceController { @Autowired private ResourceLoader resourceLoader; @RequestMapping("/dynamic/**") public ResponseEntity<Resource> getDynamicResource(HttpServletRequest request) throws IOException { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String bestMatchingPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); AntPathMatcher apm = new AntPathMatcher(); String relativePath = apm.extractPathWithinPattern(bestMatchingPattern, path); Resource resource = resourceLoader.getResource("classpath:dynamic/" + relativePath); if (!resource.exists()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return ResponseEntity.ok(resource); } } ``` 2. 在 `application.properties` 配置静态资源路径: ``` spring.mvc.static-path-pattern=/static/** ``` 3. 在 `WebMvcConfigurer` 注册 `ResourceHttpRequestHandler`: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); registry.addResourceHandler("/dynamic/**") .addResourceLocations("classpath:/dynamic/") .resourceChain(false) .addResolver(new PathResourceResolver() { @Override protected Resource getResource(String resourcePath, Resource location) throws IOException { Resource requestedResource = location.createRelative(resourcePath); if (requestedResource.exists() && requestedResource.isReadable()) { return requestedResource; } else if (resourcePath.contains(".")) { String pathPrefix = resourcePath.substring(0, resourcePath.lastIndexOf(".")); String pathSuffix = resourcePath.substring(resourcePath.lastIndexOf(".")); Resource indexResource = location.createRelative(pathPrefix + ".html"); if (indexResource.exists() && indexResource.isReadable()) { return indexResource; } } return new ClassPathResource("/dynamic/index.html"); } }); } } ``` 4. 在 `/dynamic` 目录下创建静态资源文件,例如 `/dynamic/index.html`。 5. 启动应用,访问 `http://localhost:8080/dynamic/index.html` 即可动态加载静态资源。 以上就是使用 `ResourceHttpRequestHandler` 实现动态加载静态资源的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值