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

Spring Boot设置上下文路径并实现根路径/重定向至/api

Spring Boot 根路径重定向至上下文路径解决方案

你已经通过配置server.contextPath=/api(Spring Boot 2.x及以上版本请使用server.servlet.context-path=/api)设置了应用的上下文路径,要解决根路径/访问404并实现重定向,可通过以下几种方式实现:

方法一:使用控制器实现重定向

创建一个简单的控制器,处理根路径的GET请求并返回重定向指令:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RootRedirectController {

    @GetMapping("/")
    public String redirectToApi() {
        return "redirect:/api";
    }
}

方法二:通过WebMvc配置添加视图控制器

实现WebMvcConfigurer接口,注册重定向视图控制器,无需单独写控制器类:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "/api");
    }
}

以上两种方式都会在访问/时触发3xx重定向,自动跳转到你的应用上下文路径/api,解决404问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:37:01