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

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

问题描述

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

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