Input Validation and SQL Injection Prevention
Learn input validation and SQL injection prevention in Java and Spring Boot, including Bean Validation, parameterized queries, ORM safety, allowlists, and secure query design.
What You Will Learn
- Why input validation matters.
- How SQL injection happens.
- How parameterized queries prevent injection.
- How Bean Validation helps.
- Common secure coding practices.
Introduction
Input validation protects your application from malformed, unexpected, or malicious data.
SQL injection happens when untrusted input becomes executable SQL.
SQL Injection Example
Bad pattern:
String sql = "select * from users where email = '" + email + "'";
An attacker can pass input that changes the query.
Safe Query Pattern
@Query("select u from User u where u.email = :email")
Optional<User> findByEmail(@Param("email") String email);
The parameter is bound safely instead of concatenated.
Bean Validation Example
public record CreateUserRequest(
@NotBlank
@Email
String email,
@NotBlank
@Size(min = 8, max = 72)
String password
) {}
Validation Flow
flowchart LR
A["Request"] --> B["Bean validation"]
B --> C["Business validation"]
C --> D["Parameterized query"]
D --> E["Database"]
Best Practices
- Validate at API boundaries.
- Use allowlists for known values.
- Use parameterized queries.
- Avoid dynamic SQL when possible.
- Escape only for the correct output context.
- Do not trust client-side validation.
Summary
Prevent SQL injection by validating inputs and using parameterized queries. Treat all external input as untrusted.
Learning Path Navigation
- Series home: Spring Security Learning Path
- Previous: OWASP Top 10 for Java Developers
- Next: Secure File Upload Implementation
Comments
Share a question, correction, or practical insight about this article.
Checking login status...
Loading approved comments...