1.js
function changepost(){
let id = $("#id").text()
let title = $("#title").val()
let username = $("#username").val()
let description = $("#description").val()
let password = $("#password").val()
let jsonData = { // Body에 첨부할 json 데이터
"id":id,
"username":username,
"title":title,
"description":description,
"password":password
};
console.log(description)
$.ajax({
type: "PUT",
url: '/post/detail/change',
contentType: "application/json",
data: JSON.stringify(jsonData),
success: function (response) {
alert("게시글이 수정 되었습니다.")
window.location.href = "/post/detail?id="+id
}
})
}
2.Controller
@PutMapping("/post/detail/change")
@ResponseBody
public Posting changedetail(@RequestBody Posting posting){
Posting posting1 = postingService.changedetail(posting);
return posting1;
}
3.Service
public Posting changedetail(Posting posting) {
Posting posting1 = postRepository.findById(posting.getId())
.orElseThrow(() -> new NullPointerException("해당 아이디가 존재하지 않습니다."));
posting1.setTitle(posting.getTitle());
posting1.setDescription(posting.getDescription());
posting1.setUsername(posting.getUsername());
postRepository.save(posting1);
return posting1;
}
ajax에 Posting 엔티티와 동일한 값을 담아준 후 PUT 요청을 한다.
요청을 받은 Controller는 service에 Posting을 넣어준다.
service에서는 받은 posting 에서 id값으로 db에 값을 호출한 후
setter 메소드를 통해 값을 다시 담아준다
그리고 save 한 뒤 posting 엔티티를 리턴한다.
트러블슈팅
PUT 요청에 대해 너무 강박을 가지고 했던것 같다
POST랑 똑같은데 이름만 PUT으로 바뀐 느낌?