【问题标题】:PUT method gives NULL JSONPUT 方法给出 NULL JSON
【发布时间】:2021-05-27 05:04:15
【问题描述】:
@PutMapping(path = "{studentId}")
public void updateStudent(
        @PathVariable("studentId") Long studentId,
        @RequestParam(required = false) String name,
        @RequestParam(required = false) String email){

    studentService.updateStudent(studentId, name, email);
}

@Transactional
public void updateStudent(Long studentId, String name, String email){

    Student student = studentRepository.findById(studentId)
            .orElseThrow(() -> new IllegalStateException("Student with " +studentId+" does not exist" ));


        student.setName(name);
        student.setEmail(email);
}

}

问题是当我在 POSTMAN 中执行 PUT 方法时,它没有给出错误,但“name”和“email”中的值为 NULL。我该如何解决? 这是我的 POSTMAN 请求。

https://i.stack.imgur.com/KHYVW.png

【问题讨论】:

  • 您的 api 需要可选的请求参数,并且您在邮递员中提供请求正文

标签: java spring postman


【解决方案1】:

您的 api 需要可选的请求参数,并且您在邮递员中提供请求正文。上面的 api 适用于/student/1?name=John&email=example@abc.com 如果您想使用请求正文来处理此 api,即提交表单数据,请将 api 更改为使用请求正文,这将是 (@RequestBody Student studentData),其中 Student 是具有 2 个字符串变量名称和电子邮件的类。您可以为您的 put/post api 创建一个只有请求属性的新类 StudentRequest,或者您可以重用 Student 类。

@PutMapping(path = "{studentId}")
public void updateStudent(
    @PathVariable("studentId") Long studentId,
    @RequestBody(required = true) Student student){

    studentService.updateStudent(studentId, student);
}


@Transactional
public void updateStudent(Long studentId, Student studentData){
  
     Student student = studentRepository.findById(studentId)
        .orElseThrow(() -> new IllegalStateException("Student with " +studentId+" does not exist" ));
 
     student.setName(studentData.getName());
     student.setEmail(studentData.getEmail());
     studentRepository.save(student);
}

【讨论】:

  • 据我所知,更改studentRepository.save(student);后必须在末尾有这一行来预设学生对象
  • 是的,但问题在于 api 请求。但无论如何我都会添加保存部分。
猜你喜欢
  • 2014-10-10
  • 2021-04-05
  • 1970-01-01
  • 2014-11-17
  • 2016-03-31
  • 1970-01-01
  • 2018-12-27
  • 2021-04-30
  • 1970-01-01
相关资源
最近更新 更多