Spring/Spring MVC

[Spring] HTTP 요청 맵핑 - HEAD와 OPTIONS

TheWing 2020. 11. 15. 18:04

HEAD와 OPTIONS

우리가 구현하지 않아도 스프링 웹 MVC에서 자동으로 처리하는 HTTP Method

  • HEAD
  • OPTIONS

HEAD

  • GET 요청과 동일하지만 응답 본문을 받아오지 않고 응답 헤더만 받아온다. (테스트 하기 위함)

예시

@Controller
public class SampleController {

    @GetMapping(
            value = "/hello",
            params = "name=sungjun"
    )
    @ResponseBody
    public String hello() {
        return "hello";
    }
}
@WebMvcTest
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        mockMvc.perform(get("/hello")
                .param("name","sungjun")
        )
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }
}
  • 결과

  • 이렇게 보내면 Body에 hello가 담긴다
@WebMvcTest
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        mockMvc.perform(head("/hello")
                .param("name","sungjun")
        )
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }
}

  • 이렇게 보내면 Body에 담기지 않는다

OPTIONS

  • 사용할 수 있는 HTTP Method 제공
  • 서버 또는 특정 리소스가 제공하는 기능을 확인할 수 있다.
  • 서버는 Allow 응답 헤더에 사용할 수 있는 HTTP Method 목록을 제공해야 한다.

예시

RequestMapping 일때

@Controller
public class SampleController {

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

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        mockMvc.perform(options("/hello"))
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }
}
  • 테스트 결과

Get,PostMapping 일때

@Controller
public class SampleController {

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

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

  • 테스트 결과

ALLOW 확인 예제

@WebMvcTest
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        mockMvc.perform(options("/hello"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(header().stringValues(HttpHeaders.ALLOW,
                        CoreMatchers.hasItems(
                                CoreMatchers.containsString("GET"),
                                CoreMatchers.containsString("POST"),
                                CoreMatchers.containsString("HEAD"),
                                CoreMatchers.containsString("OPTIONS")
                                )))
        ;
    }
    }
  • 테스트 결과 성공

Reference