스프링 웹 MVC-14.미디어 타입, 헤더와 매개변수(요청 맵핑하기)


HTTP 요청 맵핑하기 3부: 미디어 타입 맵핑

특정한 타입의 데이터를 담고 있는 요청만 처리하는 핸들러

  • @RequestMapping(consumes=MediaType.APPLICATION_JSON_UTF8_VALUE) // 문자열 대체 (produces=”application/json”)
  • Content-Type 헤더로 필터링
  • 매치 되는 않는 경우에 415 Unsupported Media Type 응답

특정한 타입의 응답을 만드는 핸들러

  • @RequestMapping(produces=”application/json”)
  • Accept 헤더로 필터링 (하지만 살짝… 오묘함 -> 밑에 예제 코드 참고. 선언 안한경우 요청에서는 허용)
  • 매치 되지 않는 경우에 406 Not Acceptable 응답

문자열을 입력하는 대신 MediaType을 사용하면 상수를 (IDE에서) 자동 완성으로 사용할 수 있다.

    @RequestMapping(value = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE) // 뒤에 value 붙은 경우 string
public class MediaType extends MimeType implements Serializable {
  public static final String APPLICATION_JSON_VALUE = "application/json"; 
...

클래스에 선언한 @RequestMapping에 사용한 것과 조합이 되지 않고 메소드에 사용한 @RequestMapping의 설정으로 덮어쓴다.
(우선순위가 메서드의 것으로 적용, 미선언 시에는 클래스에 선언한 것 적용.)

Not (!)을 사용해서 특정 미디어 타입이 아닌 경우로 맵핑 할 수도 있다.

    @RequestMapping(value = "/hello",
                    consumes = MediaType.APPLICATION_JSON_VALUE, // JSON 요청만 처리
                    produces = MediaType.TEXT_PLAIN_VALUE // 텍스트 타입만 리턴
    )
    @ResponseBody
    public String hello(){
        return "hello";
    }
    @Test // 성공
    public void helloTest() throws Exception {
        mockMvc.perform(get("/hello")
                .contentType(MediaType.APPLICATION_JSON))
                // accept 선언 안했으면 성공..
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }

    @Test // 실패
    public void helloTest1() throws Exception {
        mockMvc.perform(get("/hello")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)) // accept 선언 한 경우에는 필터
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }
    @Test // 실패
    public void helloTest2() throws Exception {
        mockMvc.perform(get("/hello")
                .contentType(MediaType.TEXT_PLAIN_VALUE))
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }

HTTP 요청 맵핑하기 4부: 헤더와 매개변수

특정한 헤더가 있는 요청을 처리하고 싶은 경우

  • @RequestMapping(headers = “key”)

특정한 헤더가 없는 요청을 처리하고 싶은 경우

  • @RequestMapping(headers = “!key”)

특정한 헤더 키/값이 있는 요청을 처리하고 싶은 경우

  • @RequestMapping(headers = “key=value”)

특정한 요청 매개변수 키를 가지고 있는 요청을 처리하고 싶은 경우

  • @RequestMapping(params = “a”)

특정한 요청 매개변수가 없는 요청을 처리하고 싶은 경우

  • @RequestMapping(params = “!a”)

특정한 요청 매개변수 키/값을 가지고 있는 요청을 처리하고 싶은 경우

  • @RequestMapping(params = “a=b”)
    @RequestMapping(value = "/hello",
                    // headers = HttpHeaders.ACCEPT_LANGUAGE // Accept 헤더가 있는 경우만 처리
                    // headers = HttpHeaders.AUTHORIZATION  // AUTHORIZATION 없으면 실패
                    // headers = "!" + HttpHeaders.FROM // FROM 헤더 없어야 성공
                    // headers = HttpHeaders.AUTHORIZATION + "=" + "111"// 값도 정확해야 성공
                    // params = "name" // name 이라는 파라미터가 있어야 한다.
                    params = "name=jaeuk", // 파라미터 값까지 같아야 한다.
                    
                    // headers = HttpHeaders.CONTENT_TYPE + "=" + MediaType.APPLICATION_JSON_VALUE
                    // 이걸 간편하게 하는게 consumes (윗줄 동일)
                    consumes = MediaType.APPLICATION_JSON_VALUE
    )
    @ResponseBody
    public String hello(){
        return "hello";
    }
    @Test // 성공
    public void helloTest() throws Exception {
        mockMvc.perform(get("/hello")
                //.header(HttpHeaders.FROM, "localhost"))
                //.header(HttpHeaders.AUTHORIZATION, "111"))
                .param("name", "jaeuk")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
        ;
    }





© 2019. by jaeuk