Spring Boot如何配置server.servlet.path并让根路径访问index.html?
解决方案
这里有两种简单的方法可以实现你的需求,核心思路是把根路径/的请求转发到已经能正常访问的/api/index.html,同时保留其他API端点的/api/**前缀:
方法一:添加根路径控制器
创建一个简单的控制器类,专门处理根路径的GET请求,将其转发到你的index页面:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class RootForwardController { @GetMapping("/") public String forwardToIndex() { // 转发到/api下的index.html return "forward:/api/index.html"; } }
这样当用户访问localhost:8080/时,请求会被转发到/api/index.html,完全复用你已有的静态资源配置,其他API端点依然通过localhost:8080/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) { // 把根路径映射到/api/index.html的转发视图 registry.addViewController("/").setViewName("forward:/api/index.html"); } }
注意事项
如果你的index.html里引用了其他静态资源(比如CSS、JS文件),请确保这些资源的路径是绝对路径(比如/api/css/style.css),否则转发后浏览器会从根路径/下去找这些资源,导致404错误。
内容的提问来源于stack exchange,提问作者boden
相关产品推荐
相关产品推荐

