配置 spring boot 将 404 重定向到单页应用 [英] Configure spring boot to redirect 404 to a single page app
问题描述
我想将我的 Spring Boot 应用程序配置为将任何 404 not found 请求重定向到我的单页应用程序.
例如,如果我调用不存在的 localhost:8080/asdasd/asdasdasd/asdasd
,它应该重定向到 localhost:8080/notFound
.>
问题是我有一个单页反应应用程序,它在根路径 localhost:8080/
中运行.所以spring应该重定向到localhost:8080/notFound
然后转发到/
(保持路由).
这应该可以解决问题:为路由到 /notFound
的 404 添加错误页面,并将其转发到您的 SPA(假设条目位于 /index.html
):
@Configuration公共类 WebApplicationConfig 扩展了 WebMvcConfigurerAdapter {@覆盖public void addViewControllers(ViewControllerRegistry 注册表) {registry.addViewController("/notFound").setViewName("forward:/index.html");}@豆角,扁豆公共 EmbeddedServletContainerCustomizer containerCustomizer() {返回容器 ->{container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,/未找到"));};}}
I want to configure my Spring Boot app to redirect any 404 not found request to my single page app.
For example if I am calling localhost:8080/asdasd/asdasdasd/asdasd
which is does not exist, it should redirect to 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).
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屋!