gpt4 book ai didi

java - PostMapping Service Rest with Spring boot错误请求方法 'POST'不支持

转载 作者:行者123 更新时间:2023-11-30 06:46:14 29 4
gpt4 key购买 nike

我没有找出问题所在。

Controller

@RestController("/api")
public class CoordenadaController {

@Autowired private RepositorioCoordenada repositorioCoordenada;

@PostMapping("/salvar")
public void save(String nome, int coordenadaX, int coordenadaY) {
this.repositorioCoordenada.save(new Coordenada(nome, coordenadaX, coordenadaY));
System.out.println("Salvou.....");
}
}

PostMan 客户端

url localhost:8080/api/salvar?nome=Igreja&coordenadaX=10&coordenadaY=20

记录 PostMan 客户端错误

{
"timestamp": 1493257315171,
"status": 405,
"error": "Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/api/salvar"
}

Spring 日志错误

Request method 'POST' not supported
2017-04-26 22:41:55.168 WARN 8388 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported

如果您删除@RestController中的/api,则使用@Post注释的方法可以工作

localhost:8080/salvar?nome=Igreja&coordenadaX=10&coordenadaY=20

最佳答案

您将 POST 与 GET 混合在一起。如果你想进行 POST 操作,请执行以下操作:

@RestController("/api")
public class CoordenadaController {

@Autowired private RepositorioCoordenada repositorioCoordenada;

@PostMapping("/salvar")
public void save(@RequestBody Payload payload) {
this.repositorioCoordenada.save(new Coordenada(payload.nome, payload.coordenadaX, payload.coordenadaY));
System.out.println("Salvou.....");
}

}

public class Payload{
String nome, int coordenadaX, int coordenadaY

//getters & setters
}

然后相应地使用postmant:使用post方法,创建一个json负载并将其添加到Body部分

json 负载:

{
"nome": "bla bla",
"coordenadaX": "1",
"coordenadaY": "2"
}

您可以查看 spring 教程以获取更多信息:https://spring.io/guides/gs/rest-service/

关于java - PostMapping Service Rest with Spring boot错误请求方法 'POST'不支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43647309/

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