【问题标题】:Spring Boot Post and Get Request not workingSpring Boot Post 和 Get 请求不起作用
【发布时间】:2022-01-26 08:29:59
【问题描述】:

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

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

但是,每当我尝试发送 get 请求时,它都会返回

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

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

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);
    }

}

【问题讨论】:

  • 请只发布与问题相关的代码。
  • 如果可能的话,你能分享一下 git 链接吗?
  • 抱歉,这是 gitlab 教程链接,包含所有基本代码:gitlab.com/geektechniquestudios/learning.30
  • 在本教程中,它旨在生成一个随机 UUID,但是,我想这样做,以便我可以发送一个自定义字符串的发布请求。就像我给出的例子一样。
  • 哪个映射给出了不正确的答案? getAllPeople 还是 getPersonById?

标签: java spring spring-boot postman


【解决方案1】:

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

控制器的变化

首先,当按价格检索人员时,它将是一个列表,而不是可选的。相同的原因是多个项目(在本例中为人)可以以相同的价格出现。

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

  @GetMapping(path = "{price}")
  public List<Person> getPersonByPrice(@PathVariable("price") String price) {
    return personService.getPersonByPrice(price);
  }
 

假个人数据访问服务的变化

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

  @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

【讨论】:

  • @Kaxaura 有帮助吗?
  • 我相信是这样,我只是想对现有代码进行更改以使其正常工作。
  • 当然!我感谢所有的帮助,我仍在努力让它最终发挥作用。如果可能,请您分享一个存储库吗?
  • 我尝试只推送到那个,好像我没有访问权限,我会和你分享链接。
  • 太棒了!有用!非常感谢大家的帮助,我现在可以开始实施其他方法了。
猜你喜欢
  • 2017-08-10
  • 2015-09-30
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 2018-08-06
  • 2021-02-13
  • 2023-03-22
  • 2020-09-12
相关资源
最近更新 更多