使用postman和curl测试spring引导后端post请求

lskq00tm  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(523)

我一直在尝试测试一些简单的get和post请求方法,通过命令行使用postman和curl。
出于某种原因,当我尝试创建一个json文件并通过postman发送它时,它会将所有数据保存到第一个变量中。

我不知道发生了什么事。前端将通过json文件交付所有内容,因此如果这不起作用,那么我想在完成控制器之前修复它。
这是我的药物模型:

@Entity
@Table(name = "pharmaceuticals")
public class Pharmaceutical {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "genericName")
    private String genericName;

    @Column(name = "brandNames")
    private ArrayList<String> brandNames;

    @Column(name = "strength" )
    private String strength;

    @Column(name = "quantity")
    private Integer quantity; 

    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                CascadeType.MERGE,
                CascadeType.REFRESH
            })

    @JoinTable(name = "pharm_commonuses",
        joinColumns = { @JoinColumn(name = "pharmaceutical_id") },
        inverseJoinColumns = { @JoinColumn(name = "commonUse_id") })
    private Set<CommonUse> commonUses = new HashSet<>();

    public Pharmaceutical() {}

    public Pharmaceutical(String genericName, ArrayList<String> brandNames, String strength,
            Integer quantity) {
        this.genericName = genericName;
        this.brandNames = brandNames;
        this.strength = strength;
        this.quantity = quantity;
    }
    //getters and setters

这是我的控制器:

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class PharmaceuticalController {

    @Autowired
    PharmaceuticalRepository pharmRepository;
    CommonUseRepository comRepository;

    @GetMapping("/pharmaceuticals")
    public ResponseEntity<List<Pharmaceutical>> getPharmaceuticals(@RequestParam(required = false) String title){
        List<Pharmaceutical> pharms = new ArrayList<Pharmaceutical>();
        pharmRepository.findAll().forEach(pharms::add);
        return new ResponseEntity<>(pharms, HttpStatus.OK);
    } 

    @PostMapping("/pharmaceuticals")
    public ResponseEntity<Pharmaceutical> createPharmaceutical(@RequestBody String generic, ArrayList<String> brands, String strength, Integer quant, ArrayList<String> common){
        Pharmaceutical newPharm = new Pharmaceutical(generic, brands, strength, quant);
        for (String name: common) {
            CommonUse com = new CommonUse(name);
            comRepository.save(com);
            newPharm.getCommonUses().add(com);
        }
        pharmRepository.save(newPharm);
        return new ResponseEntity<>(newPharm, HttpStatus.CREATED);
    }
}

任何帮助都太好了!

ig9co6j1

ig9co6j11#

这就是你的问题:

@RequestBody String generic

你是说进来的身体,应该放在这根绳子里。
您应该为要发送的实体构建对象表示,并将其更改为:

@RequestBody PharmaceuticalRequest generic

然后删除 createPharmaceutical 功能。
参考文献:https://www.baeldung.com/spring-request-response-body#@请求主体

相关问题