Springboot项目,访问请求报404错误的问题解决

278人浏览 / 0人评论 / 添加收藏

1、问题描述

写了一个简单的springboot项目,在启动的时候idea未报错,浏览器访问接口时报如下的错误:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Mar 02 17:37:16 CST 2025
There was an unexpected error (type=Not Found, status=404).
No message available


2、问题解决

2.1 确认端口
   打开application.yml查看端口,我的项目是8088
server:
   port: 8088

2.2 层级是否写对
要从static下开始写,如我要访问page下的login就要访问localhost:8088/page/login.html

2.3 确保controller被spring 容器扫描到
     spring boot默认扫描的类是 在启动类的当前包和下级包。比如:我的启动类(WxshopApplication)在com.example下(com.example.WxshopApplication)那么spring 会扫描com.example和 com.example.* 如果你的controller这两个的下面的话,就不会被扫描到,就会发生404错误。
   另外一种方法是, 配置spring扫描路径来解决问题:在启动类的上面添加 @ComponentScan(basePackages = {"com.example.*"}), 这配置的controller所在的包,重新编译运行后成功调用controller下的接口。


 

见上图中,在启动类中配置@ComponentScan(basePackages = {"com.example.controller"})

这样就解决了请求访问报404的问题了。希望以上可以帮助到你!

 

备注:pom.xml中对于依赖也是很重要的,如果你的依赖和我不一致,可以参考如下的依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<version>2.7.18</version>
</dependency>
<!-- 页面渲染我们使用thymeleaf,这应该和freemarker是差不多的,都是模板引擎-->
<!-- 优点:它是一个自然化语言,编写的语言前端可以直接使用,方便前后人员的分工合作-->
<!-- 缺点:性能比其他模板引擎要低一点,但是我们在生产环境开启了它的缓存功能,性能也是很高的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.7.18</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.7.18</version>
</dependency>
</dependencies>

 

全部评论