강의를 듣다가 update는 Restful의 putMapping 이고 이것을 이용해서 사용자 정보수정을 해보라고 하였다.
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을 리턴해준다.
@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으로 바꾸어주니 당연히 성공이 나왔고,
사용자를 조회해주니 제대로 잘 수정도 되었다!