PathVariable(경로 변수) 사용
최근 HTTP API는 다음과 같이 리소스 경로에 식벽자를 넣는 스타일을 선호한다
- /mapping/userA
- /users/1
이때 @PathVariable을 사용하면 매칭되는 부분을 편리하게 조회할 수 있다.
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingpath userId={}", data);
return "ok" // RestController 사용
이때 PathVarialbe의 변수명과 파라미터의 이름이 같으면 () 부분을 다음과 같이 생략할 수 있다
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String userId) {
log.info("mappingpath userId={}", data);
return "ok" // RestController 사용
PathVariable은 아래와 같이 다중 사용이 가능하다
@Getmapping("/mapping/users/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable Long orderId){
log.info("mappingPath userId={}, orderId={}, userId, orderId);
return "ok";
}
특정 파라미터 조건 매칭
특정 파라미터가 있거나 없는 조건을 추가할 수 있다.
/**
* 파라미터로 추가 매핑
* params="mode", mode라는 파라미터가 있을 때
* params="!mode" mode라는 파라미터가 없을 때
* params="mode=debug" mode라는 파라미터의 값이 debug일 때
* params="mode!=debug" (! = ) mode라는 파라미터의 값이 debug가 아닐 때
* params = {"mode=debug","data=good"} mode파라미터가 debug이고 data파라미터가 good일 때
**/
@GetMapping(value = "/mapping-param", params = "mode=debug")
public String mappingParam() {
log.info("mappingParam");
return "ok";
}
특정 헤더 조건 매핑
파라미터랑 비슷한데 HTTP header를 사용한다는 점이 다르다.
@GetMapping(value = "/mapping-header", headers = "mode=debug")
public String mappingHeader() {
log.info("mappingHeader");
return "ok";
}
header 중 key = mode value는 debug인 헤더가 있을 경우 매핑된다
미디어 타입 조건 매핑 -HTTP요청 Content-Type, consume
@PostMapping(value = "/mapping-consume", consumes = "application/json")
public String mappingConsumes() {
log.info("mappingConsumes");
return "ok";
}
HTTP요청의 Content-Type이 매칭될 경우 매핑한다
위 코드는 HTTP요청 메세지의 Content-Type이 application/json인 경우 매핑된다
HTTP 요청을 서버 입장에서는 소비하기 때문에 consume 명령어가 사용된다.
미디어 타입 조건 매핑 -HTTP 요청 Accept, produce
@PostMapping(value = "/mapping-produce", produces = "text/html")
public String mappingProduces() {
log.info("mappingProduces");
return "ok";
}
HTTP 요청 메세지의 Accept header기준으로 매핑한다
서버에서 제공하는 것이기 때문에 produces가 사용된다.
출처 : 스프링MVC 1편 - 백엔드 웹 개발 핵심 기술 김영한
'스프링MVC' 카테고리의 다른 글
HTTP 응답 - 정적 리소스, 뷰 템플릿 (0) | 2023.08.23 |
---|---|
HTTP 요청 -기본, 헤더, 데이터 조회 (0) | 2023.08.22 |
로깅 간단하게 알아보기 (0) | 2023.08.18 |
스프링 MVC 시작하기 (0) | 2023.08.10 |
뷰 리졸버 (0) | 2023.08.08 |