@PathVariable

  • 요청 URI 패턴의 일부를 핸들러 메소드의 아규먼트로 받는 방법.

    @GetMapping("/events/{id}")
    @ResponseBody
    public Event getEvent1(@PathVariable Integer id) {
        Event event = new Event();
        event.setId(id);
        return event;
    }
    
  • 타입 변환을 지원한다.
  • (기본) 값이 반드시 있어야 한다.

    Whether the path variable is required. Defaults to true, leading to an exception being thrown if the path variable is missing in the incoming request. Switch this to false if you prefer a null or Java 8 java.util.Optional in this case. e.g. on a ModelAttribute method which serves for different requests. Since: 4.3.3

  • java의 Optional을 사용할 수 있다.

테스트 코드

@Test
public void postEventsTest() throws Exception {
    mockMvc.perform(get("/events/10"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("name").value("testName"));
}

댓글남기기