/example, /example/ 모두 허용/example 만 허용@RequestMapping({"/example", "/example2", "/example3"})
@RestController
public class RequestMappingController {
@RequestMapping(value = "/v1", method = RequestMethod.GET)
public String exampleV1() {
return "this is sparta!";
}
}
this is sparta!
405 Method Not Allowed
@RequestMapping(method = RequestMethod.GET)을 사용@GetMapping("/v2")
public String exampleV2() {
return "this is sparta!";
}
@RequestMapping(method = RequestMethod.GET)을 내부적으로 포함하고 있음@PostMapping("/post")
public String create() { return "Created!"; }
@PutMapping("/put")
public String update() { return "Updated!"; }
@DeleteMapping("/delete")
public String delete() { return "Deleted!"; }
| 어노테이션 | 적용 대상 | 특징 |
|---|---|---|
@RequestMapping | Class, Method | URL 패턴 및 HTTP Method 지정 가능 |
@GetMapping | Method | GET 요청 전용 |
@PostMapping | Method | POST 요청 전용 |
@PutMapping | Method | PUT 요청 전용 |
@DeleteMapping | Method | DELETE 요청 전용 |
@RestController
@RequestMapping("/posts")
public class PathVariableController {
@GetMapping("/{postId}")
public String getPost(@PathVariable("postId") Long id) {
return "Post ID: " + id;
}
}
Post ID: 1
@GetMapping("/{postId}/comments/{commentId}")
public String getComment(@PathVariable Long postId, @PathVariable Long commentId) {
return "Post ID: " + postId + ", Comment ID: " + commentId;
}
Post ID: 1, Comment ID: 10
@GetMapping("/{postId}")
public String pathVariableV2(@PathVariable Long postId) {
return "Post ID: " + postId;
}
@GetMapping("/{postId}/comments/{commentId}")
public String pathVariableV3(@PathVariable Long postId, @PathVariable Long commentId) {
return "Post ID: " + postId + ", Comment ID: " + commentId;
}
| 기능 | HTTP Method | URL 패턴 |
|---|---|---|
| 게시글 생성 | POST | /posts |
| 게시글 조회 | GET | /posts/{postId} |
| 게시글 수정 | PUT | /posts/{postId} |
| 게시글 삭제 | DELETE | /posts/{postId} |
| 댓글 작성 | POST | /posts/{postId}/comments |
| 댓글 조회 | GET | /posts/{postId}/comments |
| 댓글 수정 | PUT | /posts/{postId}/comments/{commentId} |
| 댓글 삭제 | DELETE | /posts/{postId}/comments/{commentId} |
☞ @RequestMapping은 클래스 레벨에서 공통 URL을 정의할 때 유용하며, 개별 메서드에는 @GetMapping 등의 축약형 Annotation을 사용하는 것이 일반적임
@GetMapping(value = "/users", params = "gender=man")
public String params() {
return "params API가 호출 되었습니다.";
}
http://localhost:8080/users?gender=man 요청 시 실행됨params API가 호출 되었습니다.
파라미터가 없으면 400 Bad Request 에러 발생
추가 속성 작성 규칙
params = "gender" → gender라는 key만 존재해야 실행됨params = "!gender" → gender라는 key가 없어야 실행됨params = "gender=man" → gender=man 값이 정확히 일치해야 실행됨params = "gender!=man" → gender 값이 man이 아니어야 실행됨params = {"gender=man", "gender=woman"} → gender 값이 man 또는 woman인 경우 실행됨@PostMapping(value = "/users", headers = "Content-Type=application/json")
public String headers() {
return "headers API가 호출 되었습니다.";
}
Content-Type=application/json이 포함되어야 실행됨application/jsonheaders API가 호출 되었습니다.@PostMapping(value = "/users", consumes = "application/json")
public String consumes() {
return "consumes API가 호출 되었습니다.";
}
Content-Type: application/json 요청 시 실행됨
추가 속성 작성 규칙
consumes="application/json" → application/json 미디어 타입만 허용consumes="!application/json" → application/json이 아닌 미디어 타입만 허용consumes="application/*" → application/로 시작하는 모든 미디어 타입 허용consumes="*/\*" → 모든 미디어 타입 허용@GetMapping(value = "/users", produces = "text/plain")
public String produces() {
return "text/plain 데이터 응답";
}
Accept: text/plain 요청 시 실행됨@Slf4j
@RestController
public class RequestHeaderController {
@GetMapping("/request/headers")
public String headers(
HttpServletRequest request,
HttpServletResponse response,
@RequestHeader MultiValueMap<String, String> headerMap,
@RequestHeader("host") String host,
@CookieValue(value = "cookie", required = false) String cookie,
HttpMethod httpMethod,
Locale locale
) {
log.info("request={}", request);
log.info("response={}", response);
log.info("headerMap={}", headerMap);
log.info("host={}", host);
log.info("cookie={}", cookie);
log.info("httpMethod={}", httpMethod);
log.info("Locale={}", locale);
return "success";
}
}
http://localhost:8080/request/headers 요청request=HttpServletRequest 객체
response=HttpServletResponse 객체
headerMap={user-agent=[PostmanRuntime], accept=[*/*], host=[localhost:8080]}
host=localhost:8080
cookie=null
httpMethod=GET
Locale=ko_KR
MultiValueMap<String, String> linkedMultiValueMap = new LinkedMultiValueMap<>();
linkedMultiValueMap.add("key1", "value1");
linkedMultiValueMap.add("key1", "value2");
List<String> values = linkedMultiValueMap.get("key1");
key1=value1&key1=value2 형태로 요청 시 key1에 두 개의 값이 저장됨