配置Spring Boot以将404重定向到单页应用 [英] Configure spring boot to redirect 404 to a single page app
问题描述
我想配置我的Spring Boot应用程序以将任何404未找到的请求重定向到我的单页应用程序.
I want to configure my Spring Boot app to redirect any 404 not found request to my single page app.
例如,如果我呼叫不存在的localhost:8080/asdasd/asdasdasd/asdasd
,它应该重定向到localhost:8080/notFound
.
For example if I am calling localhost:8080/asdasd/asdasdasd/asdasd
which is does not exist, it should redirect to localhost:8080/notFound
.
问题是我只有一个页面react应用程序,并且它在根路径localhost:8080/
中运行.因此,spring应该重定向到localhost:8080/notFound
,然后转发到/
(以保持路由).
The problem is that I have a single page react app and it runs in the root path localhost:8080/
. So spring should redirect to localhost:8080/notFound
and then forward to /
(to keep route).
推荐答案
这应该可以解决问题:为404添加一个错误页面,该页面路由到/notFound
,然后将其转发到您的SPA(假设条目位于
This should do the trick: Add an error page for 404 that routes to /notFound
, and forward that to your SPA (assuming the entry is on /index.html
):
@Configuration
public class WebApplicationConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/notFound").setViewName("forward:/index.html");
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/notFound"));
};
}
}
这篇关于配置Spring Boot以将404重定向到单页应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!