@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
@RequestMapping("/hello-basic")
public String helloBasic() {
log.info("helloBasic");
return "ok";
}
}
배열을 이용해 다중 설정을 제공할 수 있다.
@RequestMapping({"/hello-basic", "/hello-go"})
허용 범위
/hello-basic으로 매핑해놓고 /hello-basic/으로 요청해도 같은 요청으로 매핑한다.
메서드 속성
GET 등 HTTP 메서드를 지정하지 않으면 뭘로 요청하든 무관하게 호출된다.
HTTP 메서드 매핑
@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
public String mappingGetV1() {
log.info("mappingGetV1");
return "ok";
}
@GetMapping(value = "/mapping-get-v2")
public String mappingGetV2() {
log.info("mapping-get-v2");
return "ok";
}
}
해당 HTTP 메서드로 요청하지 않으면 405 Method Not Allowed를 보낸다.
경로 변수(PathVariable)
@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
/*
* /mapping/userA 이런 식으로 경로 자체에 값이 있는 것
* */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
/* 변수명이 같으면 생략 가능하다. */
@GetMapping("/mapping/{userId}")
public String mappingPath2(@PathVariable String userId) {
log.info("mappingPath userId={}", userId);
return "ok";
}
}
최근 HTTP API는 이처럼 리소스 경로에 식별자를 넣는 스타일을 선호한다.
/users/1
?를 넣는 쿼리 스트링과는 다르다.
@PathVariable의 이름과 파라미터의 이름이 같으면 생략할 수 있다.
그렇다고 애너테이션 자체를 생략할 수는 없다.
다중 사용
@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
@GetMapping("/mapping/users/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
log.info("mappingPath userId={}, orderId={}", userId, orderId);
return "ok";
}
}