springboot-module-2/
├── src/
│ └── main/
│ ├── java/
│ │ └── com.example.module2/
│ │ ├── controller/
│ │ │ └── UserController.java
│ │ ├── model/
│ │ │ └── User.java
│ │ └── SpringBootModule2Application.java
│ └── resources/
│ └── application.properties
├── README.md
└── pom.xml
Created
April 23, 2025 17:05
-
-
Save kavicastelo/219ba3ae92e83aeba6f375b09b877adf to your computer and use it in GitHub Desktop.
Spring Boot Learning Module 2 – POST Requests + Request Body + Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <dependency> | |
| <groupId>jakarta.validation</groupId> | |
| <artifactId>jakarta.validation-api</artifactId> | |
| </dependency> | |
| <dependency> | |
| <groupId>org.springframework.boot</groupId> | |
| <artifactId>spring-boot-starter-validation</artifactId> | |
| </dependency> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class User { | |
| @NotBlank(message = "Name is required") | |
| private String name; | |
| @Email(message = "Invalid email format") | |
| private String email; | |
| @Min(value = 18, message = "Minimum age is 18") | |
| private int age; | |
| // getters and setters | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @RestController | |
| @RequestMapping("/api/users") | |
| public class UserController { | |
| @PostMapping | |
| public ResponseEntity<String> createUser(@Valid @RequestBody User user) { | |
| return ResponseEntity.ok("User created: " + user.getName()); | |
| } | |
| @ExceptionHandler(MethodArgumentNotValidException.class) | |
| public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) { | |
| Map<String, String> errors = new HashMap<>(); | |
| ex.getBindingResult().getFieldErrors().forEach(error -> | |
| errors.put(error.getField(), error.getDefaultMessage())); | |
| return ResponseEntity.badRequest().body(errors); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment