SPRING/스프링 MVC

요청 맵핑하기 1부 : HTTP METHOD

JUMP개발자 2021. 6. 20. 14:41

HTTP Method 

- GET, POST, PUT, PATCH, DELETE

 

GET 요청 

- 클라이언트가 서버의 리소스를 요청할 때 사용한다. 

- 캐싱 할 수 있다. (조건적인 GET으로 바뀔 수 있다.) 

- 브라우저 기록에 남는다. 

- 북마크 할 수 있다. 

- 민감한 데이터를 보낼 때 사용하지 말 것. (URL에 다 보이기 때문.) 

- idempotent 

 

idempotent 이란 ? : 연산을 여러 번 적용하더라도 결과가 달라지지 않는 성질을 의미함 

ex:) 로그인페이지는 몇번을 호출해도 똑같으니, idempotent함. 로그인 후 나오는 메인 페이지는 환경설정 등에 따라 달라질 수 있기 때문에 idempotent하지 않음.

 

POST 요청 

- 클라이언트가 서버의 리소스를 수정하거나 새로 만들 때 사용한다. 

- 서버에 보내는 데이터를 POST 요청 본문에 담는다. 

- 캐시할 수 없다. 

- 브라우저 기록에 남지 않는다. 

- 북마크 할 수 없다. 

- 데이터 길이 제한이 없다. 

 

PUT 요청 

- URI에 해당하는 데이터를 새로 만들거나 수정할 때 사용한다. 

- POST와 다른 점은 “URI”에 대한 의미가 다르다. 

   - POST의 URI는 보내는 데이터를 처리할 리소스를 지칭하며 

   - PUT의 URI는 보내는 데이터에 해당하는 리소스를 지칭한다.

ex :) 동일한 create 요청을 2번 보내면, POST는 2번 create하지만, PUT은 1번은 CREATE하고 1번은 기존 데이터를 교체한다. 

- Idempotent 

 

PATCH 요청 

- PUT과 비슷하지만, 기존 엔티티와 새 데이터의 차이점만 보낸다는 차이가 있다. ● Idempotent 

 

DELETE 요청 

- URI에 해당하는 리소스를 삭제할 때 사용한다. 

- Idempotent 

 

스프링 웹 MVC에서 HTTP Method 맵핑하기

  • @RequestMapping(method=RequestMethod.GET)
  • @RequestMapping(method={RequestMethod.GET, RequestMethod.POST})
  • @GetMapping, @PostMapping 
@Controller
public class SampleController {

    //@GetMapping("/hello")
    //@PostMapping("/hello")
    //@RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.PUT})
    @RequestMapping(value = "/hello", method = {RequestMethod.GET})
    @ResponseBody
    public String hello() {
        return "hello";
    }

}

 

테스트 코드

@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        mockMvc.perform(get("/hello"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string("hello"));

        mockMvc.perform(post("/hello"))
                .andDo(print())
                .andExpect(status().isMethodNotAllowed());

        mockMvc.perform(put("/hello"))
                .andDo(print())
                .andExpect(status().isMethodNotAllowed());

    }


}

-> get 메서드일 때만 /hello가 url 요청이 정상 호출되는 지에 대한 테스트.