You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot整合React时出现Circular View Path异常,多层路径无法返回index.html

问题根因

你返回的是相对路径视图名index.html,Spring MVC默认会将视图名与当前请求路径拼接生成实际的视图路径。当请求单层路径/user时,拼接后路径为/MartServer/index.html,对应根目录下的静态文件可正常访问;当请求多级路径/portal/user时,拼接后路径为/MartServer/portal/index.html,该路径刚好匹配你配置的/portal/**规则,会再次调用当前Controller方法,形成循环调用,抛出异常。

解决方案

方案1:修改Controller返回值(最简单快速)

将返回值修改为绝对路径转发,强制指向根目录的index.html,避免相对路径拼接:

public String react() throws Exception {
    return "forward:/index.html";
}

方案2:统一静态资源拦截配置(更优雅,无需维护RequestMapping路径)

直接通过资源处理器配置实现:所有请求优先匹配静态资源(js、css、图片等),匹配不到的全部返回index.html,完全可以替代你现有的ReactWebController,无需手动维护所有前端路由路径:

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.IOException;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        // 静态资源存在则返回,不存在则返回index.html交给前端路由处理
                        return requestedResource.exists() && requestedResource.isReadable() 
                                ? requestedResource 
                                : new ClassPathResource("/static/index.html");
                    }
                });
    }
}

额外必做配置

  • React项目package.json添加homepage配置,适配后端上下文路径:
    "homepage": "/MartServer"
    
    否则打包后生成的静态资源引用为相对路径,在多级路由下会出现404。
  • 确认React打包后的所有产物(js、css、index.html、assets等)全部放在后端项目的src/main/resources/static目录下。

内容的提问来源于stack exchange,提问作者sb29595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:21:01