0Pricing
Spring Boot 4 Microservices & REST APIs · บทเรียน

การตรวจสอบคำขอและการตอบกลับ

ตรวจสอบข้อมูลของคำขอขาเข้าและจัดรูปแบบการตอบกลับข้อผิดพลาดให้สอดคล้องกัน

การตรวจสอบคำขอและการตอบกลับ เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Validate Requests?

When building REST APIs, clients send data to your server. This data often needs to meet certain rules, like a field not being empty, or a number being within a specific range.

  • Data Integrity: Ensures your database stores only valid information.
  • Security: Prevents malicious or malformed data from causing issues.
  • User Experience: Provides clear, immediate feedback to clients when their input is incorrect.

Validation is crucial for robust and reliable APIs.

Spring's Validation Tools

Spring Boot makes data validation easy by integrating with the Jakarta Bean Validation API (JSR 380). You'll primarily use the @Valid annotation in your controller methods.

Common validation annotations include:

  • @NotNull: Field must not be null.
  • @NotBlank: String must not be null and must contain at least one non-whitespace character.
  • @Size(min=X, max=Y): String or collection size must be within range.
  • @Min(X), @Max(Y): Numeric value must be within range.
  • @Email: String must be a valid email format.

Data Transfer Objects (DTOs)

For incoming request bodies, it's best practice to use a Data Transfer Object (DTO). A DTO is a simple Java class that mirrors the structure of the data you expect from the client.

You apply validation annotations directly to the fields within your DTO. This keeps your controller clean and separates validation logic from business logic.

Implementing Basic Validation

Let's create a ProductRequest DTO with some validation rules and use it in a Spring Boot controller. The @Valid annotation triggers the validation.

Try sending a request with an empty name or a price less than 1.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Min;

// DTO for product creation request
class ProductRequest {
    @NotBlank
    private String name;
    @Min(1)
    private double price;

    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}

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

    @PostMapping
    public String createProduct(@Valid @RequestBody ProductRequest productRequest) {
        // If validation passes, process the product request
        return "Product '" + productRequest.getName() + 
               "' with price " + productRequest.getPrice() + 
               " created successfully!";
    }
}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Customizing Error Messages

The default validation error messages can sometimes be generic. You can provide your own custom messages for each annotation to make them more user-friendly and specific to your application.

Just add the message attribute to the validation annotation, like this: @NotBlank(message="Product name is required").

Custom Message Example

Let's update our ProductRequest DTO to include custom error messages. This helps clients understand exactly what went wrong with their input.

Run this and try the previous invalid inputs again. You should see your custom messages.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Min;

// DTO for product creation request with custom messages
class ProductRequest {
    @NotBlank(message = "Product name cannot be empty")
    private String name;
    @Min(value = 1, message = "Product price must be at least 1")
    private double price;

    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}

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

    @PostMapping
    public String createProduct(@Valid @RequestBody ProductRequest productRequest) {
        return "Product '" + productRequest.getName() + 
               "' with price " + productRequest.getPrice() + 
               " created successfully!";
    }
}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Handling Validation Exceptions

When validation fails, Spring automatically throws a MethodArgumentNotValidException. By default, Spring handles this by returning an HTTP 400 Bad Request status with a simple error body.

However, for a consistent API, you'll want to customize this error response. This means catching the exception and formatting the response in a structured way, often with specific error codes or details.

Global Error Handler

To provide a uniform error response across your entire API, you can use a Global Error Handler. This is typically a class annotated with @ControllerAdvice.

Inside this class, you define methods annotated with @ExceptionHandler to catch specific exception types, like MethodArgumentNotValidException, and return a custom ResponseEntity.

Error Handling in Action

Here's how to create a global error handler that catches validation exceptions and returns a structured JSON error response. This improves API consistency and makes error handling easier for clients.

Run this code and try sending an invalid product request. Observe the structured error response.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Min;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Map;

// DTO for product creation request
class ProductRequest {
    @NotBlank(message = "Product name cannot be empty")
    private String name;
    @Min(value = 1, message = "Product price must be at least 1")
    private double price;

    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}

// Custom Error Response DTO
class ErrorResponse {
    private int status;
    private String message;
    private Map<String, String> errors;

    public ErrorResponse(int status, String message, Map<String, String> errors) {
        this.status = status;
        this.message = message;
        this.errors = errors;
    }

    // Getters
    public int getStatus() { return status; }
    public String getMessage() { return message; }
    public Map<String, String> getErrors() { return errors; }
}

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

    @PostMapping
    public String createProduct(@Valid @RequestBody ProductRequest productRequest) {
        return "Product '" + productRequest.getName() + 
               "' with price " + productRequest.getPrice() + 
               " created successfully!";
    }
}

@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<ErrorResponse> handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        ErrorResponse errorResponse = new ErrorResponse(
            HttpStatus.BAD_REQUEST.value(), 
            "Validation failed", 
            errors
        );
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Validation Quick Check

Consider a DTO field: @Size(min = 5, max = 10, message = "Length must be between 5 and 10") String code;

Which input for code would cause a validation error?

Recap: Validation & Errors

In this lesson, you learned how to implement robust request validation in Spring Boot and provide consistent error responses.

  • We used @Valid and standard bean validation annotations like @NotBlank and @Min with DTOs.
  • You saw how to customize validation error messages.
  • We implemented a @ControllerAdvice global error handler to catch MethodArgumentNotValidException and return structured, user-friendly error responses.

Well done! Consistent validation and error handling are key for a professional API.

คำถามที่พบบ่อย

บทเรียน “การตรวจสอบคำขอและการตอบกลับ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจสอบคำขอและการตอบกลับ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบคำขอและการตอบกลับ”

ตรวจสอบข้อมูลของคำขอขาเข้าและจัดรูปแบบการตอบกลับข้อผิดพลาดให้สอดคล้องกัน คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน

บทเรียน “การตรวจสอบคำขอและการตอบกลับ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตรวจสอบคำขอและการตอบกลับ
  2. การแบ่งหน้าและการเรียงลำดับ
  3. หลักการ HATEOAS สำหรับ REST
← กลับไปที่ Spring Boot 4 Microservices & REST APIs