[Spring 입문] Request Mapping

박화랑·2025년 3월 18일

Spring_개념정리

목록 보기
14/17

Request Mapping 1강

1. @RequestMapping

  • 특정 URL로 Request를 보내면 들어온 요청을 Controller 내부의 특정 Method와 Mapping하기 위해 사용
  • Client로부터 요청이 왔을 때 URL뿐만 아니라 HTTP Method 등의 요소를 조합하여 Mapping 가능

@RequestMapping 특징

  1. Spring Boot 3.0 이하/example, /example/ 모두 허용
  2. Spring Boot 3.0 이상/example 만 허용
  3. HTTP Method를 지정하지 않으면 모든 메서드(POST, GET, PUT, PATCH, DELETE, HEAD) 허용
  4. 배열 형태로 다중 URL 매핑 가능
@RequestMapping({"/example", "/example2", "/example3"})

예제 코드

@RestController
public class RequestMappingController {

    @RequestMapping(value = "/v1", method = RequestMethod.GET)
    public String exampleV1() {
        return "this is sparta!";
    }
}

실행 결과 (GET 요청)

this is sparta!

실행 결과 (POST, PUT 등 허용되지 않은 요청)

405 Method Not Allowed

2. HTTP Method별 Mapping Annotation

1) @GetMapping

  • 내부적으로 @RequestMapping(method = RequestMethod.GET)을 사용
  • GET 요청을 간결하게 매핑할 수 있음
@GetMapping("/v2")
public String exampleV2() {
    return "this is sparta!";
}

@GetMapping 내부 구조

  • @RequestMapping(method = RequestMethod.GET)을 내부적으로 포함하고 있음
  • Method Level에서만 사용 가능

2) @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

  • 각각의 HTTP Method를 처리하는 전용 Annotation
@PostMapping("/post")
public String create() { return "Created!"; }

@PutMapping("/put")
public String update() { return "Updated!"; }

@DeleteMapping("/delete")
public String delete() { return "Deleted!"; }

3) @RequestMapping과의 차이

어노테이션적용 대상특징
@RequestMappingClass, MethodURL 패턴 및 HTTP Method 지정 가능
@GetMappingMethodGET 요청 전용
@PostMappingMethodPOST 요청 전용
@PutMappingMethodPUT 요청 전용
@DeleteMappingMethodDELETE 요청 전용

3. @PathVariable

  • URL 경로에서 값을 추출하여 파라미터로 전달하는 역할 수행
  • Restful API 설계에서 자주 사용됨

@PathVariable 사용 예시

@RestController
@RequestMapping("/posts")
public class PathVariableController {

    @GetMapping("/{postId}")
    public String getPost(@PathVariable("postId") Long id) {
        return "Post ID: " + id;
    }
}

실행 결과 (GET /posts/1)

Post ID: 1

@PathVariable 여러 개 사용

@GetMapping("/{postId}/comments/{commentId}")
public String getComment(@PathVariable Long postId, @PathVariable Long commentId) {
    return "Post ID: " + postId + ", Comment ID: " + commentId;
}

실행 결과 (GET /posts/1/comments/10)

Post ID: 1, Comment ID: 10

@PathVariable 규칙

  1. 파라미터 변수명과 PathVariable 변수명이 같으면 속성 값 생략 가능
@GetMapping("/{postId}")
public String pathVariableV2(@PathVariable Long postId) {
    return "Post ID: " + postId;
}
  1. 여러 개의 @PathVariable 사용 가능
@GetMapping("/{postId}/comments/{commentId}")
public String pathVariableV3(@PathVariable Long postId, @PathVariable Long commentId) {
    return "Post ID: " + postId + ", Comment ID: " + commentId;
}

4. Restful API 설계 예시

기능HTTP MethodURL 패턴
게시글 생성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을 사용하는 것이 일반적임


Request Mapping 2강

1. 특정 파라미터 매핑

  • 속성 설정을 통해 특정 파라미터와 Mapping 가능

1) 특정 파라미터 추가 매핑

@GetMapping(value = "/users", params = "gender=man")
public String params() {
    return "params API가 호출 되었습니다.";
}
  • http://localhost:8080/users?gender=man 요청 시 실행됨

실행 결과

params API가 호출 되었습니다.
  • 파라미터가 없으면 400 Bad Request 에러 발생

  • 추가 속성 작성 규칙

    1. params = "gender" → gender라는 key만 존재해야 실행됨
    2. params = "!gender" → gender라는 key가 없어야 실행됨
    3. params = "gender=man" → gender=man 값이 정확히 일치해야 실행됨
    4. params = "gender!=man" → gender 값이 man이 아니어야 실행됨
    5. params = {"gender=man", "gender=woman"} → gender 값이 man 또는 woman인 경우 실행됨

2) 특정 Header 매핑

@PostMapping(value = "/users", headers = "Content-Type=application/json")
public String headers() {
    return "headers API가 호출 되었습니다.";
}
  • 요청 Header에 Content-Type=application/json이 포함되어야 실행됨

Postman 요청 예시

  • Headers → Content-Type → Value: application/json
  • 실행 결과: headers API가 호출 되었습니다.

2. MediaType 매핑

1) consumes (요청 Content-Type 매핑)

@PostMapping(value = "/users", consumes = "application/json")
public String consumes() {
    return "consumes API가 호출 되었습니다.";
}
  • Content-Type: application/json 요청 시 실행됨

  • 추가 속성 작성 규칙

    1. consumes="application/json" → application/json 미디어 타입만 허용
    2. consumes="!application/json" → application/json이 아닌 미디어 타입만 허용
    3. consumes="application/*" → application/로 시작하는 모든 미디어 타입 허용
    4. consumes="*/\*" → 모든 미디어 타입 허용

2) produces (응답 Content-Type 매핑)

@GetMapping(value = "/users", produces = "text/plain")
public String produces() {
    return "text/plain 데이터 응답";
}
  • Accept: text/plain 요청 시 실행됨

3. HTTP 헤더 조회

@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";
    }
}

Postman 요청 예시

  • 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

4. MultiValueMap 사용

  • HTTP Header 및 Request Parameter에서 다중 값을 받을 때 사용
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에 두 개의 값이 저장됨
profile
개발자 희망생

0개의 댓글