Skip to content

Instantly share code, notes, and snippets.

@godoway
Last active September 21, 2018 09:23
Show Gist options
  • Select an option

  • Save godoway/ab4a6ce06949b2fe18e1f7c4c99e0943 to your computer and use it in GitHub Desktop.

Select an option

Save godoway/ab4a6ce06949b2fe18e1f7c4c99e0943 to your computer and use it in GitHub Desktop.
解决angular在springboot中刷新导致404的问题,其根源在于需要将所有error page都重定向到angular的路由
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
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;
import java.util.Arrays;
@Configuration
public class StaticResourcesConfiguration implements WebMvcConfigurer {
static final String[] STATIC_RESOURCES = new String[]{
"/**/*.css",
"/**/*.html",
"/**/*.js",
"/**/*.json",
"/**/*.bmp",
"/**/*.jpeg",
"/**/*.jpg",
"/**/*.png",
"/**/*.ttf",
"/**/*.eot",
"/**/*.svg",
"/**/*.woff",
"/**/*.woff2"
};
private final ResourceProperties resourceProperties;
@Autowired
public StaticResourcesConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Add all static files
registry.addResourceHandler(STATIC_RESOURCES)
.addResourceLocations(resourceProperties.getStaticLocations());
System.out.println(Arrays.toString(resourceProperties.getStaticLocations()));
//Create mapping to index.html for Angular HTML5 mode.
String[] indexLocations = getIndexLocations();
registry.addResourceHandler("/**")
.addResourceLocations(indexLocations)
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
return location.exists() && location.isReadable() ? location : null;
}
});
}
private String[] getIndexLocations() {
return Arrays.stream(resourceProperties.getStaticLocations())
.map((location) -> location + "index.html")
.toArray(String[]::new);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment