• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

PutMapping 과제 한번 확인해 주실 수 있나요?

20.10.14 15:50 작성 조회수 317

0

안녕하세요. 강의 정말 잘 듣고있습니다.

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

지현명님의 프로필

지현명

2021.06.26

여기 강의까지 jpa 진도가 나가지 않았는데 put에 대한 답을 jpa보다 기존 강의 내용과 같은 내용으로 하는게 좋지 않을까 싶습니다. 

0

SJkim님의 프로필

SJkim

2020.10.16

안녕하세요 위에 댓글 남긴 사람입니다.
생각보다 간단히 풀려서 공유하려고 댓글 남깁니다.

set할때 indexof를 써서 인덱스넘버로 기준을 잡으면 해결되는 문제였네요.

0

SJkim님의 프로필

SJkim

2020.10.16

안녕하세요 저도 putmapping 과제로 만들어 보다가 해결못한 점이 있어 댓글 남깁니다.

가령 postmapping 으로 id:4 를 만들고 deletemapping 으로 id: 3을 지우면 arraylist 사이즈가 3이 됩니다.

여기서 putmapping으로 id:4를 수정하면 setName, setJoinDate로 수정할때 기준이 id가 되면 arraylist에

index를 벗어나게 되는데 해결하셨는지 문의드려요.