[英]Error while trying to use post metod in springboot
I'm learning Spring Boot rn and I'm getting errors on my way when I'm trying to use POST method.我正在学习 Spring Boot rn,当我尝试使用 POST 方法时出现错误。
HTTP code is 400. HTTP 代码为 400。
Here is the code of my rest controller c:这是我的 rest controller c 的代码:
package com.example.carsapi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.awt.*;
import java.util.Optional;
@RestController
@RequestMapping("/cars")
public class CarRestController {
private final CarService carService;
@Autowired
public CarRestController(CarService carService) {
this.carService = carService;
}
@GetMapping
public ResponseEntity<List> getCars(){
return new ResponseEntity(carService.findAllCars(), HttpStatus.OK);
}
@GetMapping(value = "/id/{id}")
public ResponseEntity<List> getCarById(@PathVariable Integer id){
Optional<CarDTO> found = carService.findAllCars().stream().filter(car -> car.getCarId() == id).findFirst();
if(found.isPresent()){
return new ResponseEntity(found.get(), HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/color/{color}")
public ResponseEntity<List> getCarByColor(@PathVariable String color){
Optional<CarDTO> found = carService.findAllCars().stream().filter(car -> car.getColor().equals(color)).findFirst();
if(found.isPresent()){
return new ResponseEntity(found.get(), HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@PostMapping(value = "/add")
public ResponseEntity addCar(@RequestBody CarDTO car){
carService.findAllCars().add(car);
return new ResponseEntity(HttpStatus.CREATED);
}
}
And there is my JSON code which I'm using:还有我正在使用的 JSON 代码:
[
{
"carId": 3,
"carBrand": "Audi",
"carModel": "RS6",
"color": "red"
}
]
Hope you'll help me I had even tried with @RequestParam
, getting all of the values like id
, brand
, model
and color
and then adding a new object with these values which I've got from the query but it still didn't work.希望你能帮助我,我什至尝试过使用
@RequestParam
,获取所有值,如id
、 brand
、 model
和color
,然后添加一个新的 object ,这些值是我从查询中获得的,但它仍然没有工作。
The request is an array while CarDTO
is a single object.请求是一个数组,而
CarDTO
是单个 object。 You can make the request with a body like this(notice the absence of []
):您可以使用这样的主体发出请求(注意没有
[]
):
{
"carId": 3,
"carBrand": "Audi",
"carModel": "RS6",
"color": "red"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.