SpringBoot动态加载静态资源
时间: 2023-08-23 09:47:52 浏览: 158
SpingBoot-Web静态资源.zip
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` 实现动态加载静态资源的方法。
阅读全文