Bird
Raised Fist0
Spring Bootframework~10 mins

Request DTO for input in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Request DTO for input
Client sends HTTP request
Spring Boot Controller receives request
Request body parsed into DTO object
Controller method uses DTO for processing
Response generated and sent back
The client sends data in a request, Spring Boot converts it into a DTO object, which the controller uses to process the input.
Execution Sample
Spring Boot
public record UserRequestDTO(String name, int age) {}

@PostMapping("/user")
public ResponseEntity<String> addUser(@RequestBody UserRequestDTO user) {
    return ResponseEntity.ok("User " + user.name() + " added");
}
This code defines a DTO to receive user data and a controller method that accepts it from the request body.
Execution Table
StepActionInput DataDTO StateController Output
1Receive HTTP POST /user{"name":"Alice","age":30}nullnull
2Parse JSON to DTO{"name":"Alice","age":30}UserRequestDTO[name=Alice, age=30]null
3Call controller method with DTOUserRequestDTO[name=Alice, age=30]UserRequestDTO[name=Alice, age=30]null
4Process DTO and create responseUserRequestDTO[name=Alice, age=30]UserRequestDTO[name=Alice, age=30]"User Alice added"
5Send HTTP responsenullUserRequestDTO[name=Alice, age=30]"User Alice added"
💡 Request processed and response sent back to client
Variable Tracker
VariableStartAfter Step 2After Step 3Final
usernullUserRequestDTO[name=Alice, age=30]UserRequestDTO[name=Alice, age=30]UserRequestDTO[name=Alice, age=30]
responsenullnullnull"User Alice added"
Key Moments - 2 Insights
Why does the controller method parameter have @RequestBody annotation?
The @RequestBody tells Spring Boot to convert the incoming JSON into the DTO object before calling the method, as shown in execution_table step 2.
What happens if the JSON keys don't match DTO fields?
Spring Boot will fail to map those fields, and the DTO fields will be null or default, causing possible errors. This is seen in step 2 where parsing sets the DTO state.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the DTO state after step 2?
AUserRequestDTO[name=Bob, age=25]
Bnull
CUserRequestDTO[name=Alice, age=30]
DEmpty DTO object
💡 Hint
Check the 'DTO State' column in row for step 2 in execution_table
At which step does the controller method receive the DTO object?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column describing method call in execution_table
If the input JSON was missing the 'age' field, how would the DTO state change after step 2?
ADTO would have age=0 (default int value)
BDTO would have age=null
CParsing would fail and DTO would be null
DDTO would have age=some random value
💡 Hint
Primitive int fields default to 0 if missing in JSON, as per Java behavior
Concept Snapshot
Request DTO in Spring Boot:
- Define a record or class with fields for input data
- Use @RequestBody in controller method parameter
- Spring Boot auto-converts JSON to DTO
- Controller uses DTO to process input
- Response sent back after processing
Full Transcript
In Spring Boot, when a client sends data in an HTTP request, the controller can receive this data as a Request DTO. The DTO is a simple object or record that holds the input fields. The @RequestBody annotation tells Spring Boot to convert the JSON request body into this DTO object automatically. The controller method then uses this DTO to process the input and generate a response. This flow ensures clean separation of input data and business logic.

Practice

(1/5)
1. What is the main purpose of a Request DTO in a Spring Boot application?
easy
A. To configure the application server settings
B. To store data directly in the database
C. To handle HTTP responses sent to the client
D. To organize and validate user input separately from database models

Solution

  1. Step 1: Understand what a Request DTO is

    A Request DTO (Data Transfer Object) is used to receive and organize input data from users in a clean way.
  2. Step 2: Differentiate from other components

    Unlike database models, Request DTOs focus only on input validation and structure, not on storing data.
  3. Final Answer:

    To organize and validate user input separately from database models -> Option D
  4. Quick Check:

    Request DTO = Input organization and validation [OK]
Hint: Request DTOs separate input from database models [OK]
Common Mistakes:
  • Confusing DTO with database entity
  • Thinking DTO handles HTTP responses
  • Assuming DTO configures server
2. Which of the following is the correct way to declare a simple Request DTO class in Spring Boot to receive a user's name and age?
easy
A. public interface UserRequest { String getName(); int getAge(); }
B. public class UserRequest { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
C. @Entity public class UserRequest { private String name; private int age; }
D. @Controller public class UserRequest { private String name; private int age; }

Solution

  1. Step 1: Identify the correct DTO structure

    A Request DTO is a simple Java class with private fields and public getters/setters to hold input data.
  2. Step 2: Check annotations and class type

    It should NOT be an entity or controller; those are for database and web layers respectively.
  3. Final Answer:

    Plain Java class with private fields and getters/setters -> Option B
  4. Quick Check:

    DTO = Plain class with getters/setters [OK]
Hint: DTOs are plain classes, not entities or controllers [OK]
Common Mistakes:
  • Using @Entity annotation on DTO
  • Making DTO an interface
  • Annotating DTO as @Controller
3. Given the following Request DTO and controller method, what will be the output if the JSON input is {"name":"Alice","age":30}?
public class UserRequest {
  private String name;
  private int age;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
  public int getAge() { return age; }
  public void setAge(int age) { this.age = age; }
}

@PostMapping("/user")
public String createUser(@RequestBody UserRequest request) {
  return "User: " + request.getName() + ", Age: " + request.getAge();
}
medium
A. User: null, Age: 0
B. Compilation error due to missing annotations
C. User: Alice, Age: 30
D. Runtime error due to invalid JSON

Solution

  1. Step 1: Understand JSON to DTO mapping

    The JSON keys match the DTO fields, so Spring Boot maps "name" to name and "age" to age correctly.
  2. Step 2: Check controller return value

    The method returns a string combining name and age from the DTO, so it outputs "User: Alice, Age: 30".
  3. Final Answer:

    User: Alice, Age: 30 -> Option C
  4. Quick Check:

    Matching JSON fields produce correct output [OK]
Hint: Matching JSON keys to DTO fields maps input correctly [OK]
Common Mistakes:
  • Assuming missing annotations cause errors
  • Expecting null values despite matching JSON
  • Confusing runtime errors with mapping
4. Identify the error in this Request DTO class that causes Spring Boot to fail binding JSON input:
public class ProductRequest {
  private String productName;
  private int quantity;
  public int getQuantity() { return quantity; }
  public void setQuantity(int quantity) { this.quantity = quantity; }
}
medium
A. Missing getter and setter for productName field
B. Quantity field should be public
C. Class must be annotated with @RequestBody
D. No default constructor defined

Solution

  1. Step 1: Check field access and methods

    productName lacks getter/setter, so Spring cannot bind JSON to it properly.
  2. Step 2: Validate other options

    Quantity has proper getter/setter; @RequestBody is for method parameters, not classes; default constructor is implicit.
  3. Final Answer:

    Missing getter and setter for productName field -> Option A
  4. Quick Check:

    DTO fields need getters/setters for binding [OK]
Hint: DTO fields need getters/setters for JSON binding [OK]
Common Mistakes:
  • Thinking public fields bind without getters/setters
  • Adding @RequestBody on DTO class
  • Assuming default constructor must be explicit
5. You want to ensure that the email field in your Request DTO is not empty and follows a valid email format. Which annotations should you add to the email field to achieve this validation automatically in Spring Boot?
hard
A. @NotEmpty and @Email
B. @Valid and @NotNull
C. @Size(min=1) and @Pattern(regexp=".+@.+\\..+")
D. @NotBlank and @JsonProperty

Solution

  1. Step 1: Identify validation annotations for non-empty and email format

    @NotEmpty ensures the field is not empty, and @Email checks for valid email format.
  2. Step 2: Evaluate other options

    @Valid is for nested validation, @NotNull allows empty strings, @Size and @Pattern can work but are more complex; @JsonProperty is for JSON mapping, not validation.
  3. Final Answer:

    @NotEmpty and @Email -> Option A
  4. Quick Check:

    Use @NotEmpty and @Email for email validation [OK]
Hint: Use @NotEmpty and @Email for email validation [OK]
Common Mistakes:
  • Using @NotNull which allows empty strings
  • Confusing @Valid with validation annotations
  • Using @JsonProperty for validation