Validation in Spring Boot
Last Updated :
26 Apr, 2025
In this article, via a Gradle project, let us see how to validate a sample application and show the output in the browser. The application is prepared as of type Spring Boot and in this article let us see how to execute via the command line as well.
Example Project
Project Structure:
As this is the Gradle project, we need to check for
build.gradle
buildscript {
ext {
springBootVersion = '2.3.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'gfg'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 8
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
// This is very much essential for validation
implementation('org.springframework.boot:spring-boot-starter-validation')
implementation('org.springframework.boot:spring-boot-starter-web')
runtimeOnly('com.h2database:h2')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testImplementation('org.junit.jupiter:junit-jupiter-engine:5.0.1')
// these dependencies are needed when running with Java 11, since they
// are no longer part of the JDK
implementation('javax.xml.bind:jaxb-api:2.3.1')
implementation('org.javassist:javassist:3.23.1-GA')
}
test{
useJUnitPlatform()
}
gradlew.bat (Gradle startup script for Windows)
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NULL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Now let us see the main application file from which the application starts to execute
SampleValidationApplication.java
Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleValidationApplication {
public static void main(String[] args) {
SpringApplication.run(SampleValidationApplication.class, args);
}
}
Let us see the necessary files that are helpful to produce the validation errors in a meaningful and clear way
ErrorHandlingControllerAdviceSample.java
Java
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
class ErrorHandlingControllerAdviceSample {
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ValidationErrorResponse onConstraintValidationException(ConstraintViolationException e) {
ValidationErrorResponse error = new ValidationErrorResponse();
for (ConstraintViolation violation : e.getConstraintViolations()) {
error.getViolations().add(new Violation(violation.getPropertyPath().toString(), violation.getMessage()));
}
return error;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ValidationErrorResponse onMethodArgumentNotValidException(MethodArgumentNotValidException e) {
ValidationErrorResponse error = new ValidationErrorResponse();
for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
error.getViolations().add(new Violation(fieldError.getField(), fieldError.getDefaultMessage()));
}
return error;
}
}
ValidationErrorResponse.java
Java
import java.util.ArrayList;
import java.util.List;
public class ValidationErrorResponse {
private List<Violation> violations = new ArrayList<>();
public List<Violation> getViolations() {
return violations;
}
public void setViolations(List<Violation> violations) {
this.violations = violations;
}
}
Violation.java
Java
public class Violation {
private final String fieldName;
private final String message;
public Violation(String fieldName, String message) {
this.fieldName = fieldName;
this.message = message;
}
public String getFieldName() {
return fieldName;
}
public String getMessage() {
return message;
}
}
ValidateGivenParametersByController.java
This is the controller file where we can put the annotations for conditional checking
Java
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.validation.constraints.Email;
import javax.validation.constraints.Positive;
import javax.validation.constraints.NegativeOrZero;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
class ValidateGivenParametersByController {
@GetMapping("/validatePathVariable/{id}")
ResponseEntity<String> validatePathVariable(@PathVariable("id") @Min(5) int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameterWithMin")
ResponseEntity<String> validateRequestParameterWithMin(@RequestParam("id") @Min(0) int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameterWithMax")
ResponseEntity<String> validateRequestParameterWithMax(@RequestParam("id") @Max(5) int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameterWithEmailId")
ResponseEntity<String> validateRequestParameterWithEmailId(@Email @RequestParam(name = "emailId") String emailId) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameterWithPositive")
ResponseEntity<String> validateRequestParameterWithPositive(@Positive @RequestParam(name = "id") int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameterWithNegativeOrZero")
ResponseEntity<String> validateRequestParameterWithNegativeOrZero(@NegativeOrZero @RequestParam(name = "id") int id) {
return ResponseEntity.ok("valid");
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
String handleConstraintViolationException(ConstraintViolationException e) {
return "Given input is not valid due to validation error: " + e.getMessage();
}
}
Via the command line, we can execute the project as follows
Now let us test the following
Test 1:
http://localhost:8080/validatePathVariable/90
This is valid as we have the code as id should be @Min(5)). At the same time, if we pass as
http://localhost:8080/validatePathVariable/1
the error will be thrown
Test 2:
http://localhost:8080/validateRequestParameterWithMin?id=-10
Here @Min(0) is applied and hence we can see below the validation error message
Test 3:
http://localhost:8080/validateRequestParameterWithMax?id=10
Here @Max(5) is applied and hence
Test 4:
http://localhost:8080/validateRequestParameterWithEmailId?emailId=a.com
Here emailId is not properly given
Test 5:
http://localhost:8080/validateRequestParameterWithPositive?id=-200
So only positive numbers alone are accepted
Test 6:
http://localhost:8080/validateRequestParameterWithNegativeOrZero?id=100
So only negative or zero only accepted
Conclusion
Throughout the entire project, we can use the necessary annotation and validate the input fields. We also can give a proper error message and make the software more productive.
Similar Reads
How to Create Todo List API using Spring Boot and MySQL?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
6 min read
Spring Boot - Transaction Management Using @Transactional Annotation
The @Transactional annotation is the metadata used for managing transactions in the Spring Boot application. To configure Spring Transaction, this annotation can be applied at the class level or method level. In an enterprise application, a transaction is a sequence of actions performed by the appli
9 min read
Spring Boot - Map Entity to DTO using ModelMapper
In enterprise applications, we use RESTful services to establish the communication between client and server. The general idea is that the client sends the request to the server and the server responds to that request with some response. Generally, we have three different layers in most of the appli
8 min read
Spring Boot | How to consume JSON messages using Apache Kafka
Apache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer
3 min read
Spring Boot | How to consume string messages using Apache Kafka
Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application. Appro
3 min read
Spring Boot | How to publish String messages on Apache Kafka
Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, r
2 min read
Spring Boot | How to publish JSON messages on Apache Kafka
Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref
4 min read
Spring Boot - Consume JSON Object From Kafka Topics
Apache Kafka is a publish-subscribe messaging system. A messaging system lets someone is sending messages between processes, applications, and servers. Broadly Speaking, Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. Applications may connect
4 min read
Spring Boot Kafka Producer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read