You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java RequestMapping问题:Postman调用/chat接口返回404错误

解决GET请求/chat返回404的问题

咱们先从几个最常见的排查方向入手,毕竟404大多和路由映射、组件扫描范围有关:

1. 检查Controller的注解配置是否正确

你在com.dogochat.chat包下的Controller类,得确保两个关键注解没漏:

package com.dogochat.chat;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;

@RestController // 必须加这个,让Spring识别为请求处理类
public class ChatController {

    @GetMapping("/chat") // 路径要和你请求的完全一致
    public List<String> getChats() {
        // 返回你预期的空列表
        return Collections.emptyList();
    }
}

要确认:

  • 类上有没有@RestController(或者用@Controller+@ResponseBody组合)
  • @GetMapping的路径是不是准确写的/chat,别多打斜杠或者拼写错误

2. 检查Spring Boot的包扫描范围

你的启动类DogoApplicationcom.dogo包下,Spring Boot默认只会扫描启动类所在包及其子包的组件。而com.dogochat.chatcom.dogo是平级包,不在默认扫描范围内,这大概率是核心问题!

解决方法有两种:

  • 方法一:把DogoApplication移到更上层的包,比如com.dogochat,这样com.dogochat.chat就成了它的子包,自动被扫描
  • 方法二:在启动类上手动指定扫描包:
package com.dogo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.dogo", "com.dogochat.chat"}) // 同时扫描两个包
public class DogoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DogoApplication.class, args);
    }
}

3. 查看项目启动日志验证路由是否注册

启动项目后,留意控制台日志里有没有类似这样的输出:

Mapped "{[/chat],methods=[GET]}" onto public java.util.List<...> com.dogochat.chat.ChatController.getChats()
  • 如果没有这条日志:说明Spring没识别到你的Controller,回到步骤2检查包扫描
  • 如果有这条日志:再确认Postman的请求细节——是不是误发了POST请求?路径是不是多打了斜杠(比如localhost:8080//chat)?

4. 确认服务器端口和上下文路径

检查application.properties/application.yml里的配置:

  • 有没有改server.port?比如设成了8081,那Postman就得用8081端口请求
  • 有没有设置server.servlet.context-path?比如设了/api,那请求路径得改成localhost:8080/api/chat

按这几步排查下来,应该能解决404的问题。

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

火山引擎 最新活动