[Spring] Request Mapping (1)

이연우·2025년 7월 22일

TIL

목록 보기
27/100

🔗 @RequestMapping

  • 특정 URL 요청을 컨트롤러 메서드에 매핑

📌 특징

  • 여러 URL 지정 가능: @RequestMapping({"/a", "/b"})
  • 모든 HTTP Method 허용 가능
  • method 속성으로 HTTP Method 제한 가능
package com.example.springbasicannotation.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

// 응답 데이터 반환
@RestController
public class RequestMappingController {

    // HTTP Method: GET만 허용
    @RequestMapping(value = "/v1", method = RequestMethod.GET)
    public String exampleV1() {
        // logic
        return "this is sparta!";
    }

}

⚠️ Spring Boot 3.0 변경 사항

  • 3.0 이하: /example, /example/ 허용
  • 3.0 이상: /example만 허용

❗ 요청 메서드 불일치 시

  • 405 Method Not Allowed 발생

📦 축약 어노테이션 (더 자주 사용됨)

어노테이션내부 동작
@GetMapping@RequestMapping(method = RequestMethod.GET)
@PostMapping@RequestMapping(method = RequestMethod.POST)
@PutMapping@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping@RequestMapping(method = RequestMethod.DELETE)
@PatchMapping@RequestMapping(method = RequestMethod.PATCH)
@GetMapping("/v2")
public String exampleV2() {
    return "this is sparta!";
}

🧱 클래스 단위의 @RequestMapping

  • URL prefix 지정용으로 사용
@RequestMapping("/prefix")
@RestController
public class RequestMappingController {

    @GetMapping("/v3")
    public String exampleV3() {
        return "this is sparta!";
    }
}

→ 📌 결과: /prefix/v3


🛣️ @PathVariable

  • URL 경로에 포함된 변수를 메서드 파라미터로 매핑
@GetMapping("/posts/{postId}")
public String getPost(@PathVariable Long postId) {
    return "Post ID: " + postId;
}

✅ 특징 및 규칙

항목설명
기본 필수값값 없으면 404 Not Found
변수명 동일 시 생략 가능@PathVariable Long postId
다중 변수 처리 가능여러 @PathVariable 조합 가능

1. 파라미터 변수명과 PathVariable 변수명이 같으면 속성 값 생략 가능

@RequestMapping("/posts")
@RestController
public class PathVariableController {
	
	// postId로 된 post 단건 조회
	@GetMapping("/{postId}")
	public String pathVariableV1(@PathVariable("postId") Long data) {
		// logic
		String result = "PathvariableV1 결과입니다 : " + data;
		return result;
	}
}

> 생략

@RequestMapping("/posts")
@RestController
public class PathVariableController {
	
	// 변수명과 같다면 속성값 생략 가능
	@GetMapping("/{postId}")
	public String pathVariableV2(@PathVariable Long postId) {
		// logic
		String result = "PathvariableV2 결과입니다 : " + postId;
		return result;
	}
	
}

2. @PathVariable 다중 사용 가능

@RestController
public class PathVariableController {
	
	@GetMapping("/{postId}/comments/{commentId}")
	public String pathVariableV3(
																@PathVariable Long postId,
																@PathVariable Long commentId
															) {
		// logic
		String result = "PathvariableV3 결과입니다 postId : " + postId + "commentsId : " + commentId;
		return result;
	}
	
}
@RequestMapping("/posts/{postId}")
@RestController
public class PathVariableController {
	
	@GetMapping("/comments/{commentId}")
	public String pathVariableV4(
																@PathVariable Long postId,
																@PathVariable Long commentId
															) {
		// logic
		String result = "PathvariableV4 결과입니다 postId : " + postId + "commentsId : " + commentId;
		return result;
	}
	
}

💻️ Restful API
REST API URI Naming Conventions and Best Practices

  • Create - POST
  • Read - GET
  • Update - PUT, PATCH
  • Delete - DELETE

🌍 Restful API 설계 예시

동작HTTPURI Path
댓글 작성POST/posts/{postId}/comments
전체 조회GET/posts/{postId}/comments
댓글 조회GET/posts/{postId}/comments/{commentId}
댓글 수정PUT/posts/{postId}/comments/{commentId}
댓글 삭제DELETE/posts/{postId}/comments/{commentId}

💡
Restful API를 설계하게 되면
URL path만으로 어떤 Resource을 사용하는지,
HTTP Method만으로 어떤 기능이 동작되는지 쉽게 알아볼 수 있음

1개의 댓글

comment-user-thumbnail
2025년 9월 9일

Truly impressed with the incredible building skills of every creator with diverse programming settings. Unlock new creations and challenges of the geometry dash lite series. A truly fun platform rhythm game world with lots of new traps and geometric designs.

답글 달기