35 lines
1.4 KiB
Java
35 lines
1.4 KiB
Java
package com.music.config;
|
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.core.io.Resource;
|
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|
import org.springframework.web.servlet.resource.PathResourceResolver;
|
|
|
|
import java.io.IOException;
|
|
|
|
/**
|
|
* 生产环境:前端 SPA 由 Spring Boot 托管时,未匹配到的路径回退到 index.html。
|
|
*/
|
|
@Configuration
|
|
public class SpaForwardConfig implements WebMvcConfigurer {
|
|
|
|
@Override
|
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
|
registry.addResourceHandler("/**")
|
|
.addResourceLocations("classpath:/static/")
|
|
.resourceChain(true)
|
|
.addResolver(new PathResourceResolver() {
|
|
@Override
|
|
protected Resource getResource(String resourcePath, Resource location) throws IOException {
|
|
Resource resource = location.createRelative(resourcePath);
|
|
if (resource.exists() && resource.isReadable()) {
|
|
return resource;
|
|
}
|
|
// SPA 路由回退到 index.html
|
|
return location.createRelative("index.html");
|
|
}
|
|
});
|
|
}
|
|
}
|