HTTP 요청 및 응답 처리
요청 매개변수, 경로 변수, 요청 본문을 처리하고 적절한 HTTP 응답을 작성하는 방법을 학습합니다.
HTTP 요청 및 응답 처리은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Requests & Responses
When you interact with a web application, your browser sends an HTTP Request to a server. The server then processes it and sends back an HTTP Response.
In Spring Boot, we write code to listen for these requests, extract information, perform actions, and then craft a suitable response.
Getting Query Params: @RequestParam
Sometimes, extra data is sent in the URL after a ?, like /search?keyword=java. These are query parameters.
Spring Boot uses the @RequestParam annotation to easily extract these values into your method parameters.
Live Demo: @RequestParam
Try running this example. After the app starts, open your browser or a tool like Postman and visit http://localhost:8080/hello?name=Coddy. See what happens!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@GetMapping("/hello")
public String sayHello(
@RequestParam(defaultValue = "Guest") String name) {
return "Hello, " + name + "!";
}
}Extracting from Path: @PathVariable
Other times, important data is part of the URL path itself, like /users/123. Here, 123 is an ID.
The @PathVariable annotation lets you capture these dynamic segments from the URL directly into your method parameters.
Live Demo: @PathVariable
Run this app, then visit http://localhost:8080/items/apple or http://localhost:8080/items/banana in your browser.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@GetMapping("/items/{itemName}")
public String getItemDetails(@PathVariable String itemName) {
return "You requested item: " + itemName;
}
}Query vs. Path: When to Use?
- @RequestParam: Use for optional filtering, sorting, or pagination (e.g.,
/products?category=books&page=1). - @PathVariable: Use for identifying a specific resource (e.g.,
/users/{id},/products/{sku}). It's essential for the resource's identity.
Handling Data Payloads: @RequestBody
For operations like creating or updating resources (POST, PUT requests), clients often send complex data (like JSON or XML) in the request body.
The @RequestBody annotation automatically converts this body content into a Java object for you, thanks to Spring's built-in message converters.
Live Demo: @RequestBody
Run this. Use a tool like Postman to send a POST request to http://localhost:8080/users with a JSON body:
{"id":1, "name":"Coddy"}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
// Define a simple User class
public static class User {
private Long id;
private String name;
// Getters and setters for JSON mapping
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
@PostMapping("/users")
public String createUser(@RequestBody User user) {
return "User created: ID=" + user.getId() +
", Name=" + user.getName();
}
}Custom Responses: ResponseEntity
By default, Spring often returns a String or a Java object, which Spring converts to JSON/XML with a 200 OK status.
For more control, especially over HTTP status codes (like 201 Created, 404 Not Found), use ResponseEntity. It lets you specify the body, status, and headers explicitly.
Quick Check: Request Handling
Consider a Spring Boot REST endpoint designed to fetch a user by their unique ID, like /api/users/5. Which annotation is best suited to extract the 5 from the URL?
Lesson Summary
We've covered how Spring Boot makes handling HTTP requests easy:
@RequestParamfor query parameters (optional data).@PathVariablefor path variables (resource identifiers).@RequestBodyfor deserializing request body content into Java objects.ResponseEntityfor fine-grained control over HTTP responses, including status codes.
Mastering these annotations is key to building robust RESTful APIs!
자주 묻는 질문
“HTTP 요청 및 응답 처리” 강의는 무료인가요?
네 — “HTTP 요청 및 응답 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“HTTP 요청 및 응답 처리”에서 뭘 배우나요?
요청 매개변수, 경로 변수, 요청 본문을 처리하고 적절한 HTTP 응답을 작성하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“HTTP 요청 및 응답 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- REST 컨트롤러 만들기
- HTTP 요청 및 응답 처리
- 입력 검증 및 오류 처리
- OpenAPI와 Swagger로 REST API 문서화