본문 바로가기

WEB개발/Spring

[Spring] Request를 처리하는 주석 (Annotation)


@RequestParam  
@PathVariable 
@RequestBody
@ModelAttribute  
@RequestHeader
@CookieValue  
@SessionAttribute  
@RequestPart

 


 

@RequestParam

?name=value 같은 쿼리 파라미터 값을 받음

 

Content-type

  • application/x-www-form-urlencoded
  • multipart/form-data
  • (쿼리 파라미터로 전달될 경우 Content-Type 상관없음)

 

@GetMapping("/greet")
public String greet(@RequestParam String name) {
    return "Hello, " + name;
}

 

 

@RequestBody

JSON, XML 등의 HTTP 요청 본문(body)을 객체로 변환하여 받음

 

Content-type

  • application/json
  • application/xml
  • text/plain (직접 파싱하면 가능)
@PostMapping("/users")
public String createUser(@RequestBody User user) {
    return "User created: " + user.getName();
}

 

@ModelAttribute

폼 데이터를 객체로 바인딩할 때 사용 (x-www-form-urlencoded)

 

Content-type

 

  • application/x-www-form-urlencoded ✅ (폼 데이터)
  • multipart/form-data ✅ (파일 포함 가능)

 

@PostMapping("/register")
public String registerUser(@ModelAttribute User user) {
    return "User registered: " + user.getName();
}

 

@PathVariable

 {value} 형태의 URL 경로 변수 값을 받음

@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
    return "User ID: " + id;
}

 

 

@RequestHeader

HTTP 요청 헤더 값을 받음

@GetMapping("/header")
public String getHeader(@RequestHeader("User-Agent") String userAgent) {
    return "User-Agent: " + userAgent;
}

 

@CookieValue

쿠키 값을 받아올 때 사용

@GetMapping("/cookie")
public String getCookie(@CookieValue(value = "sessionId", defaultValue = "unknown") String sessionId) {
    return "Session ID: " + sessionId;
}

 

@SessionAttribute

세션에서 특정 속성 값을 가져올 때 사용

@GetMapping("/session")
public String getSession(@SessionAttribute(name = "user", required = false) User user) {
    return user != null ? "User: " + user.getName() : "No session user";
}

 

@RequestPart

multipart/form-data (파일 포함)

@PostMapping(value = "/json-and-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFileWithJson(
    @RequestPart("data") User user,  // JSON 데이터를 User 객체로 받음
    @RequestPart("file") MultipartFile file
) {
    return "Received: " + user.getName() + ", File: " + file.getOriginalFilename();
}