PutMapping 과제 한번 확인해 주실 수 있나요?
621
작성한 질문수 8
안녕하세요. 강의 정말 잘 듣고있습니다.
PutMapping 과제로 내주신거 한번 해봤는데 맞는지 확인좀 부탁드려도될까요??
기본적으로 수정이라 id는 알아야 할 것 같아서 @PathVariable 로 id를 받고 body에 넣어줄 user 값은 @Requestbody로 두번째 인수로 넣었습니다.
이런 방식으로 수정하는게 맞나요..?
//Controller 코드
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User user) {
User updateUser = service.updateById(id, user);
if (updateUser == null) {
throw new UserNotFoundException(String.format("ID[%s] is not Found", id));
}
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(updateUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
//Service 코드
@Override
public User updateById(int id, User user) {
for (User updateUser : userList) {
if (updateUser.getId() == id) {
userList.get(id-1).setName(user.getName());
userList.get(id-1).setJoinDate(user.getJoinDate());
return user;
}
}
return null;
}
답변 4
2
안녕하세요, 이도원입니다.
PUT 메소드에 대한 처리는 다음과 같이 하시면 될 것 같습니다. 참고로, Response 응답 코드로 201이 아닌, 200이나 204으로 하시는게 좋습니다.
@PutMapping("/users/{id}")
public ResponseEntity<Object> updateStudent(@RequestBody User user, @PathVariable int id) {
Optional<User> userOptional = userRepository.findById(id);
if (!userOptional.isPresent())
return ResponseEntity.notFound().build();
user.setId(id);
userRepository.save(user);
return ResponseEntity.noContent().build();
}
감사합니다.
0
안녕하세요 위에 댓글 남긴 사람입니다.
생각보다 간단히 풀려서 공유하려고 댓글 남깁니다.
set할때 indexof를 써서 인덱스넘버로 기준을 잡으면 해결되는 문제였네요.
0
안녕하세요 저도 putmapping 과제로 만들어 보다가 해결못한 점이 있어 댓글 남깁니다.
가령 postmapping 으로 id:4 를 만들고 deletemapping 으로 id: 3을 지우면 arraylist 사이즈가 3이 됩니다.
여기서 putmapping으로 id:4를 수정하면 setName, setJoinDate로 수정할때 기준이 id가 되면 arraylist에
index를 벗어나게 되는데 해결하셨는지 문의드려요.
JPA
0
57
1
jpa dependency를 추가하고 SecurityConfig클래스에서 오류가 납니다.
0
68
1
웹 브라우저 400 bad request
0
71
1
@Size는 되는데 @Past는 안 됩니다.
0
61
1
pdf 자료는 없나요?
0
73
2
locale 정보가 null 이면 무조건 messages_ko.properties이 호출 되는 문제
0
87
2
Swagger 강의, Unable to infer base url 이거 뜨시는 분들 도움되시라고
0
118
1
강의에서나온 화면 피피티
0
158
1
HelloWorldBean 관련 에러
0
183
2
Swagger API 3.x 오류..
0
219
1
java: variable message not initialized in the default constructor 에러는 어찌하면 좋을까요?
1
282
1
현재 GIT에 올리신 소스를 실행해봤습니다.
0
189
2
고양이 소리가 귀엽네요 !!
0
137
2
git에서 소스받고 실습중인데
0
117
1
post가 안되요
0
102
1
한국어 같은 경우 언어코드인 messages_ko.properties 로 생성하는게 더 좋지 않나요?
0
168
2
리턴타입으로서 EntityModel<User> 와 ResponseEntity질문
0
104
1
예외처리쪽 관련 질문있습니다.
0
159
2
엔티티가 바로 응답으로 나가도 되나요??
0
221
2
안녕하세여 Cannot invoke "co.kr.joneconsulting.resfulservice.repository.PostRepository.save(Object)" because "this.postRepository" is null
0
135
2
사용자 등록하고 나서 H2 에서 보면 신규 사용자의 password, ssn 이 null 로 되어 있습니다.
0
140
2
ApplictionContext 질문
0
192
2
롬북이 안먹히는것같아요
0
156
1
인텔리제이에서스프링부트 파일 실행하면
0
240
1





