Restful PutMapping 오류 해결

매니·2022년 9월 6일
0

Restful-Web-Service

목록 보기
3/4

강의를 듣다가 update는 Restful의 putMapping 이고 이것을 이용해서 사용자 정보수정을 해보라고 하였다.

Service 코드

public User updateUser(int id, User newUser) {
    for (User user : users) {
        if(user.getId() == id) {
            user.setName(newUser.getName());
            user.setJoinDate(new Date());

            return user;
         }
    }
    return null;
}

우선 id와 User를 받아주고 기존 user 안에 id와 일치한다면 업데이트를 해주고 아니라면 null을 리턴해준다.

Controller 코드

@PutMapping("/users/{id}")
    public  void updateUser(@PathVariable int id, @RequestBody User userName) {
        User updateUser = service.updateUser(id, userName);
        if(updateUser == null) {
            throw new UserNotFoundException(String.format("ID[%s] not found", id));
        }
    }

id를 PathVariable 를 통해 받아주고 이름도 받아준다.
그리고 service 를 통해 update를 해준다.

이런식으로 코드를 작성하였고 나는

2022-09-07 01:20:22.843 DEBUG 94392 --- [nio-8088-exec-2] o.s.web.servlet.DispatcherServlet        : PUT "/users/1", parameters={}
2022-09-07 01:20:22.851 DEBUG 94392 --- [nio-8088-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.restfulwebservice.user.UserController#updateUser(int, User)
2022-09-07 01:20:22.851 DEBUG 94392 --- [nio-8088-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-09-07 01:20:22.951 DEBUG 94392 --- [nio-8088-exec-2] o.s.web.method.HandlerMethod             : Could not resolve parameter [1] in public void com.example.restfulwebservice.user.UserController.updateUser(int,com.example.restfulwebservice.user.User): Content type 'text/plain;charset=UTF-8' not supported
2022-09-07 01:20:22.953 DEBUG 94392 --- [nio-8088-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler com.example.restfulwebservice.exception.CustomizedResponseEntityExceptionHandler#handleException(Exception, WebRequest)
2022-09-07 01:20:22.964 DEBUG 94392 --- [nio-8088-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/octet-stream', given [*/*] and supported [*/*]
2022-09-07 01:20:22.966  WARN 94392 --- [nio-8088-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported]
2022-09-07 01:20:22.966 DEBUG 94392 --- [nio-8088-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-09-07 01:20:22.968 DEBUG 94392 --- [nio-8088-exec-2] o.s.web.servlet.DispatcherServlet        : Completed 415 UNSUPPORTED_MEDIA_TYPE

알수없고 길고 긴 오류를 마주할 수 있었다.

여기서 건질것은 마지막줄에 Completed 415 UNSUPPORTED_MEDIA_TYPE 이 말이다.

뜻을 해석하자면 지원되지 않는 미디어 유형이라는 뜻이고 그 말은 즉슨 보낸 데이터가 지원하지 않는 유형이라고 했다.

나는 분명 제대로 json으로 보냈는데 왜..? 라고 생각하는 찰나,

그렇다. 텍스트로 보내고 있었던 것이었다.

해결

JSON으로 바꾸어주니 당연히 성공이 나왔고,

사용자를 조회해주니 제대로 잘 수정도 되었다!


배운점

  • 오류코드는 맨 마지막줄을 읽자. 두려워하지말자. 오류안에 정답이 있을지어니~
  • 업데이트는 put과 patch 를 사용하는데 이 둘의 차이점 또한 있다.
    (간단히 설명하자면 put은 모든 정보를 update할때 사용, patch는 부분적인 정보를 update할때 사용)
  • JSON인지 제대로 확인해보자
profile
성장중 🔥

0개의 댓글

관련 채용 정보