백엔드

[Spring] @PostMapping vs @PutMapping

s_eonxx 2022. 9. 17. 23:55

일반적으로 데이터를 추가하거나 등록할 때 @PostMapping를, 수정할 때 @PutMapping을 사용한다.

 

언뜻 보아 이 둘은 새로운 요청을 서버로 전송한다는 점에서 비슷해 보인다.

 

PUT POST의 가장 큰 차이는 PUT이 가지는 멱등성으로 설명할 수 있다.

HTTP 요청에서 멱등성이란 동일한 요청을 한 번 보내는 것과 여러 번 연속해서 보내는 것에 상관없이 클라이언트가 받는 응답이 동일하다는 것을 말한다.

 

따라서, @PutMapping의 용도는 멱등성에 있다.

 

 

@PutMapping은 대상 리소스를 나타내는 데이터가 있는지 없는지 체크하여 없을 경우 Created(201) 응답을 보내고
대상 리소스를 나타내는 데이터가 있을 경우 OK(200), No Content(204) 응답을 통해 성공적으로 처리되었음을 알린다.

@PostMapping("/users/login")
    public void postlogin(@RequestParam("userid") String userid, @RequestParam("userpw") String userpw_test, HttpServletRequest request){
        int isPassed = userService.loginCheck(userid, userpw_test);

        if(isPassed==1) {
            HttpSession session = request.getSession();
            session.setAttribute("userid", userid);
            log.info("로그인 성공");
        }
        else{
            log.info("로그인 실패");
        }
    }
@PutMapping("challenges/{clgid}")
    public void modifyChallenge(@PathVariable int clgid, @RequestBody ClgDTO clgDTO){
        clgService.modifyChallenge(clgDTO);
   }