A Request DTO (Data Transfer Object) helps organize and carry data sent by users to your Spring Boot app in a simple, clear way.
Request DTO for input in Spring Boot
public class UserRequestDTO { private String name; private int age; // Getters and setters 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; } }
DTO classes usually have private fields with public getters and setters.
Spring Boot automatically converts JSON input to this DTO when used with @RequestBody.
public class LoginRequestDTO { private String username; private String password; // getters and setters }
public record ProductRequestDTO(String name, double price) {}public class RegisterRequestDTO { @NotBlank private String email; @Size(min = 6) private String password; // getters and setters }
This example shows a simple DTO class UserRequestDTO and a Spring Boot controller that accepts JSON input mapped to this DTO. When you send a POST request with JSON like {"name":"Alice","age":30}, the controller returns a confirmation message.
package com.example.demo.dto; public class UserRequestDTO { 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; } } package com.example.demo.controller; import com.example.demo.dto.UserRequestDTO; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PostMapping("/user") public String createUser(@RequestBody UserRequestDTO userRequest) { return "User " + userRequest.getName() + " aged " + userRequest.getAge() + " created."; } }
Always keep DTOs simple and focused only on data transfer.
Use validation annotations to catch bad input early.
Spring Boot automatically maps JSON fields to DTO fields by name.
Request DTOs organize user input into simple classes.
They help keep your controller code clean and easy to read.
Spring Boot maps JSON input to DTOs automatically with @RequestBody.