我正在使用postman和springboot,我已经使用了GET/POST/DELETE请求,它们都工作正常,但是PUT请求不更新内容。
在intellij中,我使用这些文件:
Student.java(with它是setter和getter):
@Entity
@Table
public class Student {
@Id
@SequenceGenerator(
name="student_sequence",
sequenceName="student_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private LocalDate dob;
private String email;
@Transient
private Integer age;
StudentController.java :
@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);
}
StudentService.java :
@Transactional
public void updateStudent(Long studentId,String name, String email)
{
Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new IllegalStateException(
"student with id="+studentId+"does not exist"));
if (name !=null && name.length()>0 && !Objects.equals(student.getName(),name))
{
student.setName(name);
}
if (email !=null && email.length()>0 && !Objects.equals(student.getEmail(),email))
{
Optional<Student> studentOptional= studentRepository.findStudentByEmail(email);
if (studentOptional.isPresent())
{
throw new IllegalStateException("email taken");
}
student.setEmail(email);
}
}
These are the students that i have in database基本上,我想更新id=1的学生的姓名和电子邮件。
That is postman header
And that is postman not showing any error after sending request
3条答案
按热度按时间a0zr77ik1#
使用
@RequestParam(required = false) String name
时,参数应作为标头或查询参数。您正在发送请求正文,因此请改用pojo ...和控制器...
6rqinv9w2#
要使它正常工作,您必须将数据作为查询参数,例如
0vvn1miw3#
因此,在回答https://stackoverflow.com/a/72698172/19354780后,我尝试将StudentController更改为:
和学生服务:
而且成功了,但没有例外。