@RequsetMapping(value = "/hello-request") 은 value에 해당하는 값인 ex) /hello-request이라는 URL 요청이 오면
해당 어노테이션이 붙은 메서드를 실행하도록 매핑한다.
@RequestMapping(value = "/hello-request")
public String helloRequest() {
return "ok";
}
즉, /hello-request로 URL 요청을 하면 helloRequest 메서드가 실행이 된다.
method 속성
@RequestMapping(value = "/hello-request", method = RequestMethod.Get)
URL 요청 방식이 method에 해당하는 요청 방식과 같아야 매핑을 해주는 역할을 한다.
@RequestMapping(value = "/hello-request", method = RequestMethod.GET)
public String helloRequest() {
return "ok";
}
예시로 /hello-request URL에 POST 방식으로 요청을 하게 되면 이미 /hello-request 은 GET 방식에만 요청을 받기로 되어 있어 405(Method Not Allowed) 에러가 발생한다.
참고로 이 method 속성을 명시하지 않고, 요청 방식에 제한을 걸어두는 방법이 있다.
GET 방식만 허용할 경우, @RequestMapping 어노테이션이 아닌 @GetMapping 어노테이션을 사용하면된다.
마찬가지로 POST 방식만 허용할 경우, @PostMapping 어노테이션을 사용하는 등등...
@GetMapping(value = "/hello-request")
public String helloRequest() {
return "ok";
}
PathVariable(경로 변수) 사용
@RequestMapping (or GetMapping, PostMapping... ) 은 URL 경로를 템플릿화 할 수 있으며, @PathVariable을 사용하여 매칭 되는 부분을 편리하게 조회가 가능하다.
@GetMapping(value = "/hello-request/{userId}")
public String helloRequest(@PathVariable("userId) String data) {
return "ok";
}
@PathVariable의 이름과 url에서 받은 파라미터의 이름이 같으면 생략이 가능하다.
@GetMapping(value = "/hello-request/{userId}")
public String helloRequest(@PathVariable String userId) {
return "ok";
}
특정 파라미터 조건 매핑
쿼리스트링 조건에 따라 매핑 연결 여부를 결정한다.
@GetMapping(value = "/hello-request", params="mode=debug")
public String helloRequest() {
return "ok";
}
이 경우는 mode 파라미터 값이 debug로 설정되어 있는 경우에 매핑을 지어준다.
특정 헤더 조건 매핑
헤더에 설정된 키값을 확인하여 매핑 연결 여부를 결정한다.
@GetMapping(value = "/hello-request", headers="mode=debug")
public String helloRequest() {
return "ok";
}
mode란 키를 가지고 그 값이 debug로 되어 있는 경우, 매핑을 지어준다.
'SPRING' 카테고리의 다른 글
@RequestBody, @ResponseBody - HTTP Message Body 조회, 반환 (0) | 2023.05.21 |
---|---|
@RequestParam @ModelAttribute - HTTP 요청 파라미터 (0) | 2023.05.17 |