gpt4 book ai didi

java - Spring Controller 被调用但返回 404

转载 作者:IT老高 更新时间:2023-10-28 13:54:36 25 4
gpt4 key购买 nike

我正在编写一个 Spring Boot 应用程序。我已经编写了一个简单的 Controller ,它会在端点被命中时被调用,但它仍然返回状态 404 而不是指定的返回值。

HelloController

@Controller
public class MessageRequestController {

@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}

现在每当我调用 localhost:8080/hello 时,我都会看到控制台日志 "Hit me!",但 "Hello, you!" code> 永远不会返回。 postman 输出:

{
"timestamp": 1516953147719,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/hello"
}

Application.java

@SpringBootApplication
@ComponentScan({"com.sergialmar.wschat"}) // this is the root package of everything
@EntityScan("com.sergialmar.wschat")
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

最佳答案

更改您的方法返回 ResponseEntity<T>

@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public ResponseEntity<String> hello() {
System.out.println("Hit me!");
return new ResponseEntity<String>("Hello, you!", HttpStatus.OK);
}

或将 Controller 更改为 RestController

@RestController
public class MessageRequestController {...}

curl

ubuntu:~$ curl -X GET localhost:8080/hello
Hello, you!

关于java - Spring Controller 被调用但返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48457939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com