Spring/Spring MVC

[Spring] HTTP 요청 맵핑 - 요청 메소드

TheWing 2020. 11. 15. 16:15

HTTP Method

  • GET, POST, PUT, PATCH, DELETE, ...

GET 요청

  • 클라이언트가 서버의 리소스를 요청할 때 사용한다.
  • 캐싱 할 수 있다. (조건적인 GET으로 바뀔 수 있다.)
  • 브라우저 기록에 남는다.
  • 북마크 할 수 있다.
  • 민감한 데이터를 보낼 때 사용하지 말 것. (URL에 다 보이니까)
  • idempotent(멱등)

Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SampleController {

    @RequestMapping("/hello")
    @ResponseBody 
    public String hello() {
        return "hello"; 
    }

}

Test

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

@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"))
                ;
    }

}

POST 요청

  • 클라이언트가 서버의 리소스를 수정하거나 새로 만들 때 사용한다.
  • 서버에 보내는 데이터를 POST 요청 본문에 담는다.
  • 캐시할 수 없다.
  • 브라우저 기록에 남지 않는다.
  • 북마크 할 수 없다.
  • 데이터 길이 제한이 없다.

PUT 요청

  • URI에 해당하는 데이터를 새로 만들거나 수정할 때 사용한다.
  • POST와 다른 점은 “URI”에 대한 의미가 다르다.
    • POST의 URI는 보내는 데이터를 처리할 리소스를 지칭하며
    • PUT의 URI는 보내는 데이터에 해당하는 리소스를 지칭한다.
  • Idempotent

PATCH 요청

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

DELETE 요청

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

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

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

    @RequestMapping(value = "/hello",method = {RequestMethod.GET,RequestMethod.PUT}) //
    @ResponseBody //문자열을 응답
    public String hello() {
        return "hello"; //해당하는 뷰를 찾는다
    }

}
  • 이렇게 클래스에 리퀘스트 매핑 겟을 설정하면 겟만가능하다

ETC

@WebMvcTest
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

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

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

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

}
  • isMethodNotAllowed()
    • 원하지 않는 값이 나올때

참고

Reference