配置Spring Boot以将404重定向到单页应用 [英] Configure spring boot to redirect 404 to a single page app

查看:535
本文介绍了配置Spring Boot以将404重定向到单页应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想配置我的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆