处理 HTTP 请求与响应
学习处理请求参数、路径变量和请求正文,并构建适当的 HTTP 响应。
处理 HTTP 请求与响应 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 请求与响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
「处理 HTTP 请求与响应」这节课中我会学到什么?
学习处理请求参数、路径变量和请求正文,并构建适当的 HTTP 响应。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Complete Guide 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「处理 HTTP 请求与响应」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?
能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。