@PathVariable
public class Event {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Controller
public class SampleController {
@GetMapping("/events/{id}")
@ResponseBody
public Event getEvent(@PathVariable Integer id){
Event event = new Event();
event.setId(id);
return event;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void getEvent() throws Exception{
mockMvc.perform(get("/events/1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
}
자바 8부터는 Optional을 쓸 수도 있다. 이렇게 되면 @PathVariable( required=false)를 준거랑 마찬가지이다.
@Controller
public class SampleController {
@GetMapping("/events/{id}")
@ResponseBody
public Event getEvent(@PathVariable Optional<Integer> id){
Event event = new Event();
event.setId(id);
return event;
}
}
@MatrixVariable
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
@Controller
public class SampleController {
@GetMapping("/events/{id}")
@ResponseBody
public Event getEvent(@PathVariable("id") Integer idValue, @MatrixVariable String name){
Event event = new Event();
event.setId(idValue);
event.setName(name);
return event;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void getEvent() throws Exception{
mockMvc.perform(get("/events/1;name=spring"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
}
참고