Nhận tham số từ request – @PathVariable, @RequestParam, @RequestBody

Mục tiêu

Sau bài này, bạn sẽ:

  • Hiểu các cách client gửi dữ liệu lên server
  • Phân biệt và sử dụng thành thạo @PathVariable, @RequestParam, @RequestBody
  • Xử lý được dữ liệu từ form HTML
  • Biết cách binding dữ liệu vào đối tượng Java

1. Các cách client gửi dữ liệu

Trong ứng dụng web, client có thể gửi dữ liệu lên server qua nhiều cách:

Cách gửiVí dụThường dùng cho
URL path/products/123Xác định tài nguyên cụ thể (ID, slug)
Query string/products?page=1&size=10Filter, phân trang, tìm kiếm
Form dataname=John&age=25Submit form HTML (thường dùng POST)
JSON body{"name":"Laptop","price":1000}API hiện đại (POST/PUT)

Trong Servlet, bạn phải tự parse từ request.getParameter(), request.getPathInfo(), hoặc đọc InputStream. Spring Boot làm việc này tự động qua các annotation.

2. So sánh với Servlet

Servlet:

// Lấy từ query string
String page = request.getParameter("page");

// Lấy từ URL path (phải tự parse)
String pathInfo = request.getPathInfo(); // "/products/123"

// Lấy từ JSON (phải đọc stream và dùng thư viện)
BufferedReader reader = request.getReader();
// ... dùng Gson/Jackson để parse

Spring Boot:

@GetMapping("/products/{id}")
public Product get(@PathVariable Long id, 
                   @RequestParam(defaultValue = "1") int page) {
    // id từ URL path, page từ query string
}

3. @PathVariable – Lấy dữ liệu từ URL path

Dùng khi giá trị là một phần của đường dẫn, thường là ID hoặc slug.

Cú pháp

@GetMapping("/products/{id}")
public Product getById(@PathVariable Long id) {
    // id = 123 nếu request là /products/123
}

@GetMapping("/categories/{categoryId}/products/{productId}")
public Product get(
        @PathVariable Long categoryId,
        @PathVariable Long productId) {
    // categoryId = 1, productId = 123 nếu request là /categories/1/products/123
}

Đặt tên khác (nếu tên biến không trùng)

@GetMapping("/products/{productId}")
public Product get(@PathVariable("productId") Long id) {
    // id = 123
}

4. @RequestParam – Lấy dữ liệu từ query string

Dùng khi dữ liệu là tham số trên URL sau dấu ?.

Cú pháp

@GetMapping("/products")
public List<Product> search(
        @RequestParam String keyword,
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(required = false) Double minPrice) {
    // Request: /products?keyword=laptop&page=2&minPrice=500
    // keyword = "laptop", page = 2, minPrice = 500
}

Các thuộc tính

  • value hoặc name: tên tham số (mặc định là tên biến)
  • required: có bắt buộc không? (mặc định true)
  • defaultValue: giá trị mặc định nếu không có
@GetMapping("/products")
public List<Product> get(
        @RequestParam(required = false) String category,
        @RequestParam(defaultValue = "0") int page) {
    // Nếu không có category -> category = null
    // Nếu không có page -> page = 0
}

5. @RequestBody – Nhận dữ liệu từ body (JSON/XML)

Dùng khi client gửi dữ liệu phức tạp dưới dạng JSON (thường là POST/PUT).

Cú pháp

@PostMapping("/products")
public Product create(@RequestBody Product product) {
    // product được tự động tạo từ JSON trong body request
    // Ví dụ body: {"name":"Laptop","price":1200}
    product.setId(1L);
    return product;
}

Nguyên lý hoạt động

  • Spring dùng Jackson (mặc định) để chuyển JSON → Java object
  • Cần có constructor không tham số và getter/setter trong class

Với nhiều tham số

@PostMapping("/orders")
public Order create(@RequestBody Order order, 
                    @RequestParam String coupon) {
    // Vừa nhận JSON, vừa nhận query param
}

6. @ModelAttribute – Binding dữ liệu từ form

Dùng khi nhận dữ liệu từ form HTML (thường là application/x-www-form-urlencoded).

Form HTML

<form action="/users" method="post">
    <input name="username" />
    <input name="email" />
    <input type="submit" />
</form>

Controller

@PostMapping("/users")
public String createUser(@ModelAttribute User user) {
    // user.username và user.email được tự động set từ form
    return "success";
}

So sánh @RequestBody vs @ModelAttribute

@RequestBody@ModelAttribute
Dữ liệuJSON/XMLForm data (application/x-www-form-urlencoded)
Content-Typeapplication/jsonapplication/x-www-form-urlencoded
Thường dùngREST APIWeb truyền thống (Thymeleaf, JSP)

7. Thực hành: API tìm kiếm sản phẩm nâng cao

Mở rộng project từ Bài trước, thêm API tìm kiếm với nhiều tham số.

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private List<Product> products = new ArrayList<>();
    // ... constructor thêm sản phẩm mẫu ...

    // GET /api/products/search?name=lap&minPrice=100&maxPrice=1000&sort=asc
    @GetMapping("/search")
    public List<Product> search(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(defaultValue = "asc") String sort) {
        
        return products.stream()
                .filter(p -> name == null || p.getName().toLowerCase().contains(name.toLowerCase()))
                .filter(p -> minPrice == null || p.getPrice() >= minPrice)
                .filter(p -> maxPrice == null || p.getPrice() <= maxPrice)
                .sorted((a, b) -> sort.equals("asc") 
                        ? a.getPrice().compareTo(b.getPrice())
                        : b.getPrice().compareTo(a.getPrice()))
                .collect(Collectors.toList());
    }
}

Test: GET /api/products/search?name=lap&minPrice=500&sort=desc

8. Thực hành: Xử lý form đăng ký người dùng

Tạo một controller trả về view (dùng Thymeleaf) để xử lý form.

Bước 1: Thêm dependency Thymeleaf

Bước 2: Tạo class User

public class User {
    private String username;
    private String email;
    private Integer age;
    // getters, setters, constructor
}

Bước 3: Tạo controller

@Controller
public class UserController {

    @GetMapping("/register")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String submitForm(@ModelAttribute User user, Model model) {
        model.addAttribute("message", "Đăng ký thành công: " + user.getUsername());
        return "result";
    }
}

Bước 4: Tạo templates/register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Đăng ký</title>
</head>
<body>
    <h2>Đăng ký tài khoản</h2>
    <form th:action="@{/register}" th:object="${user}" method="post">
        <label>Tên đăng nhập:</label>
        <input type="text" th:field="*{username}" /><br/>
        
        <label>Email:</label>
        <input type="email" th:field="*{email}" /><br/>
        
        <label>Tuổi:</label>
        <input type="number" th:field="*{age}" /><br/>
        
        <button type="submit">Đăng ký</button>
    </form>
</body>
</html>

Bước 5: Tạo templates/result.html

<!DOCTYPE html>
<html>
<head>
    <title>Kết quả</title>
</head>
<body>
    <h2 th:text="${message}"></h2>
    <a href="/register">Quay lại</a>
</body>
</html>

Chạy và truy cập: http://localhost:8080/register

9. Tổng kết

AnnotationNguồn dữ liệuThường dùng
@PathVariableURL path (/{id})Lấy ID, slug
@RequestParamQuery string (?key=value)Filter, phân trang
@RequestBodyBody (JSON)API POST/PUT
@ModelAttributeForm dataWeb form truyền thống

Quy tắc nhớ:

  • @PathVariable: thứ không thể thiếu trong URL (ID)
  • @RequestParam: thứ có thể có hoặc không (filter)
  • @RequestBody: dữ liệu phức tạp gửi lên
  • @ModelAttribute: dữ liệu từ form HTML

10. Bài tập

  1. Thêm API GET /api/products/filter với các tham số:
    • category (String, không bắt buộc)
    • inStock (Boolean, mặc định true)
    • sortBy (String, mặc định “name”)
  2. Tạo form HTML gửi dữ liệu lên API POST /api/feedback với các trường:
    • name (text)
    • email (email)
    • rating (number 1-5)
    • message (textarea)
    Dùng @ModelAttribute để nhận dữ liệu và trả về trang cảm ơn.
  3. (Nâng cao) Kết hợp cả 3 loại trong một API:
    PATCH /api/products/{id}?notify=true
    • {id} là @PathVariable
    • notify là @RequestParam
    • Body JSON chứa các trường cần cập nhật (@RequestBody)

Comments are closed.