Spring 启动 Post 和获取请求不工作

Spring Boot Post and Get Request not working

我是 Springboot 的新手,正在发出 post/get 请求,我一直在关注 youtube 教程以更好地理解它 postman。但是,我 运行 在修改代码时遇到了问题,我试图允许 post 请求 2 个条目

{
"name": "Hat",
"price": "" 
}

但是,每当我尝试向它发送 get 请求时 returns

{
"price": "null"
"name": "Hat" 
}

我认为问题在于价格未被 posted,因此 .orElse(null) 正在执行。我不确定为什么会这样,非常感谢您的帮助。如果需要任何进一步的信息,请告诉我,我会post。

package com.example.demo.dao;

import com.example.demo.model.Person;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Repository("fakeDao") //class serves as a repository
public class FakePersonDataAcessService implements PersonDao{

    private static List<Person> DB = new ArrayList<>();

    @Override
    public int insertPerson(Person/*BigDecimal*/ price, Person person) {
        DB.add(new Person(price.getPrice(), person.getName()));
        return 1;
    }

    @Override
    public List<Person> selectAllPeople() {
        return DB;
    }

    @Override
    public Optional<Person> selectPersonByPrice(Person/*BigDecimal*/ price) {
        return DB.stream()
                .filter(person -> person.getPrice().equals(price))            //filters through the people and checks our DB to see if that person with that price exists
                .findFirst();
    }

    @Override
    public int deletePersonByPrice(Person/*BigDecimal*/ price) {
        Optional<Person> personMaybe = selectPersonByPrice(price);
        if (personMaybe.isEmpty()){
            return 0;
        }
        DB.remove(personMaybe.get());
        return 1;
    }

    @Override
    public int updatePersonByPrice(Person/*BigDecimal*/ price, Person update) {
        return selectPersonByPrice(price)         //select the person
                .map(person -> {                 //map the person
                    int indexOfPersonToUpdate = DB.indexOf(person);
                    if (indexOfPersonToUpdate >= 0){                //if the index of that person is >=0 we know that we have found that person
                        DB.set(indexOfPersonToUpdate, new Person(price.getPrice(), update.getName()));      //set contents of that person to the new person that we just recieved from thc client
                        return 1;                               //return 1 if everything is fine
                    }
                    return 0;               //otherwise we return 0 or if selectpersonbyprice is not present we dont do anyhthing and just return 0
                })
                .orElse(0);
    }
}
package com.example.demo.api;

import com.example.demo.model.Person;
import com.example.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@RequestMapping("api/v1/person")
@RestController
public class PersonController {

    private final PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @PostMapping
    public void addPerson(Person price,/*@Valid @NotNull Stringprice,*/@Valid @NotNull @RequestBody Person person){
        personService.addPerson(price,/*price,*/ person);
    }

    @GetMapping
        public List<Person> getAllPeople(){
        return personService.getAllPeople();
    }
    @GetMapping(path = "{price}")
    public Person getPersonByPrice(@PathVariable("price") Person/*BigDecimal*/ price){
        return personService.getPersonByPrice(price)                  //after sending a get request with that price we will either return the person, OR if they don't exisist we return null
                .orElse(null);
    }
    @DeleteMapping(path = "{price}")
    public void deletePersonByPrice(@PathVariable("price") Person/*BigDecimal*/ price){
        personService.deletePerson(price);
    }
    @PutMapping(path = "{price}")
    public void updatePerson(@PathVariable("price") Person/*BigDecimal*/ price, @Valid @NotNull @RequestBody Person personToUpdate){
        personService.updatePerson(price, personToUpdate);
    }

}
package com.example.demo.dao;

import com.example.demo.model.Person;

import javax.swing.text.html.Option;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

//actual interface where we can define our operations allowed/contract for anyone who wants to implement this interface; and using dependecy injection we can change db easily
public interface PersonDao {

     int insertPerson(Person price, Person person);   //allows us to insert a person with a given price
/*
    default int insertPerson(Person price, Person person){
        String price = new String("$");        //without an price, its default is 0
        return insertPerson(price, person);
    }
*/
    List<Person> selectAllPeople();

    Optional<Person> selectPersonByPrice(Person/*BigDecimal*/ price);

    int deletePersonByPrice(Person/*BigDecimal*/ price);

    int updatePersonByPrice(Person/*BigDecimal*/ price, Person person);


}
package com.example.demo.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.UUID;
public class Person {

    private final String price;
    @NotBlank                   //name can't be blank
    private final String name;


    public Person(@JsonProperty("price") String /*BigDecimal*/ price,
                  @JsonProperty("name") String name) {

        this.price = price;
        this.name = name;
    }

    public String/*BigDecimal*/ getPrice() {
        return price;
    }

    public String getName() {
        return name;
    }
}
package com.example.demo.service;

import com.example.demo.dao.PersonDao;
import com.example.demo.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class PersonService {

    private final PersonDao personDao;

    @Autowired
    public PersonService(@Qualifier("fakeDao") PersonDao personDao) {
        this.personDao = personDao;
    }


    public int addPerson(Person price,/*String price,*/ Person person){
        return personDao.insertPerson(price,/*price,*/ person);
    }
@GetMapping
    public List<Person> getAllPeople(){
        return personDao.selectAllPeople();
    }

    public Optional<Person> getPersonByPrice(Person/*BigDecimal*/ price){
        return personDao.selectPersonByPrice(price);
    }
    public int deletePerson(Person/*BigDecimal*/ price){
        return personDao.deletePersonByPrice(price);
    }
    public int updatePerson(Person/*BigDecimal*/ price, Person newPerson){
        return personDao.updatePersonByPrice(price, newPerson);
    }

}

为简单起见,我将只限制我的代码添加和获取 API。

CHANGES IN CONTROLLER

首先,按价格检索人员时,它将是一个列表,而不是可选的。相同的原因是多个项目(在这种情况下,人)可以以相同的价格出现。

其次,您将价格作为 Person 而不是 String 传递,因此需要更改。简化后,这将成为您按价格

获取价格的控制器
  @GetMapping(path = "{price}")
  public List<Person> getPersonByPrice(@PathVariable("price") String price) {
    return personService.getPersonByPrice(price);
  }
 

CHANGES IN FAKE PERSON DATA ACCESS SERVICE

在这里,您需要用给定的价格迭代整个列表,每当有人匹配它时,它就会被添加到您需要的列表中。

  @Override
  public List<Person> selectPersonByPrice(String price) {

    List<Person> p = new ArrayList<>();
    Person person = new Person("", price);
    for (Person temp : DB) {
      if (temp.getPrice().equals(price)) {
        p.add(temp);
      }
    }
    return p;
  }

因此,您对该方法的声明也会在 PersonService 中更改。

实施这些更改并向 get api 发出请求后,它成功返回了一个 it