0
0
Spring Bootframework~5 mins

Why input validation is critical in Spring Boot

Choose your learning style9 modes available
Introduction

Input validation helps keep your app safe and working well by checking user data before using it.

When users submit forms with data like names, emails, or passwords.
When your app receives data from external sources or APIs.
Before saving data to a database to avoid errors or bad data.
When processing user input that affects app behavior or security.
To prevent attacks like SQL injection or cross-site scripting.
Syntax
Spring Boot
@Valid
public ResponseEntity<?> methodName(@Valid @RequestBody DataClass data) {
    // method code
}
Use @Valid annotation to trigger validation on input objects.
Combine with annotations like @NotNull, @Size on fields inside your data class.
Examples
This example shows how to add rules to fields in a data class.
Spring Boot
public class User {
    @NotNull
    @Size(min = 2, max = 30)
    private String name;

    @Email
    private String email;
}
This controller method validates the User object before processing.
Spring Boot
@PostMapping("/addUser")
public ResponseEntity<String> addUser(@Valid @RequestBody User user) {
    return ResponseEntity.ok("User added");
}
Sample Program

This Spring Boot controller defines a User class with validation rules. The addUser method checks the input before accepting it.

Spring Boot
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    public static class User {
        @NotNull(message = "Name cannot be null")
        @Size(min = 2, max = 30, message = "Name must be 2-30 characters")
        private String name;

        @Email(message = "Email should be valid")
        private String email;

        // Getters and setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    @PostMapping("/users")
    public ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        return ResponseEntity.ok("User " + user.getName() + " added successfully");
    }
}
OutputSuccess
Important Notes

Always provide clear error messages for invalid input to help users fix mistakes.

Input validation protects your app from crashes and security risks.

Combine validation with exception handling to manage invalid inputs gracefully.

Summary

Input validation checks user data to keep apps safe and stable.

Use annotations like @Valid, @NotNull, and @Email in Spring Boot.

Validate inputs before processing or saving data.