如何配置spring boot解决前端刷新不会停留在原路径问题?

  最近遇到一个前端刷新跳转问题,问题背景:项目采用velocity模板加载前端js和css,根路由是斜杆“/“,采用history模式,通过index.html文件加载。后端有一个controller接收 ”/”请求,跳转到index.html的ModelAndView。问题现象:不管在哪个页面,每当刷新页面时,总会跳到一个特定的页面。前端说跳转到该特定页面是他们的处理逻辑,要求后端刷新时必须跳往index.html,他们才能接管Url。

  因为涉及到history模式,这个问题是需要前后端配合才能解决。我们项目中没有采用nginx,用了spring boot的2版本,所以在bootstrap类或@Component类或者@Configuration类中加一个@Bean,启动时加载这个配置,让错误页跳往index.html:

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
                factory.setErrorPages(error404Page);
            }
        };
    }

  如果是spring boot的1版本,用这种方式:

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            container.addErrorPages(error404Page);
        };
    }

  当光配置错误页跳往index.html还不行,前端要求所有path路径都跳往该index.html,所以我又把后端的这个接入“/”的controller改为接入“/**”,通过加通配符的方式,让前端所有请求都先到index.html,再通过index.html把控制权交还给前端,就能实现刷新时停留在原页面,而不是跳往一个特定的页面去了。

原文地址:https://www.cnblogs.com/wuxun1997/p/14975073.html