spring boot支持vue history mode(即增加对404的处理)

时间:2024-03-27 13:45:07

原本的问题是这样的,用大前端(Vue全家桶),静态文件直接放在Spring Boot的static文件夹里,启动后,假设访问http://localhost/page1/page1_1,如果直接点浏览器刷新按钮,会出现404,为了解决这种问题,Vue的官方文档有介绍解决方案。参考HTML5 History 模式
spring boot支持vue history mode(即增加对404的处理)
可惜的是,文档下面没有给出Java做服务器的情况下如何做。
那么,在Spring Boot做后端的情况下,怎么解决呢?这里参考 vue-router路由使用 history 模式时,后端SpringBoot如何配置
加一个配置类

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

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