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

Spring Boot控制器@RequestMapping与@GetMapping配置引发404错误求助

Spring MVC控制器404问题排查与解决

问题描述

我是Spring绝对新手,尝试实现简单控制器程序。项目中static文件夹下的index.html可通过localhost:8080正常访问,但访问localhost:8080/welcome/home时出现404白标错误,期望该路径返回index.html或显示"index"。应用启动无报错。

相关代码

Employee实体类

package model;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Employee {

    private String id;
    private String name;
    private String email;

}

控制器类

@Controller
@RequestMapping("/welcome")
public class HomeController {
    
    @GetMapping("/home")
    public String getHome() {
        return "index";
    }
}

问题原因与解决方法

1. 视图解析逻辑不匹配

你控制器返回"index"时,Spring MVC默认会去找模板引擎(比如Thymeleaf)对应的模板文件,而不是static目录下的静态HTML。如果没引入模板引擎,自然找不到视图,触发404。

两种解决路径:

  • 用模板引擎(推荐)
    以Thymeleaf为例,在Maven的pom.xml里加依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

    把index.html从static目录移到src/main/resources/templates下,Spring就能正确识别这个视图。

  • 直接返回静态文件
    不想用模板引擎的话,修改控制器方法,直接指定静态文件路径或者重定向:

    @GetMapping("/home")
    public String getHome() {
        // 直接指向static下的index.html
        return "classpath:/static/index.html";
        // 或者重定向到根路径的index.html
        // return "redirect:/index.html";
    }
    

2. 控制器未被Spring扫描到

如果HomeController所在的包不在主启动类的同级或子包下,Spring会扫不到这个控制器。解决方法是在主启动类上加上@ComponentScan指定扫描包:

@SpringBootApplication
@ComponentScan(basePackages = {"你的控制器所在包路径", "model"})
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

3. 自定义配置覆盖了默认规则

如果项目里有自定义的WebMvcConfigurer配置,检查是否修改了静态资源映射或视图解析规则,确保没有覆盖Spring的默认逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:40:05