EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot Validation
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot Validation

Spring Boot Validation

Introduction to Spring Boot Validation

In Spring boot, we can easily apply validation; it is much easier than the spring framework. We have a validator in spring boot, and it is quite straightforward to use as well. To use this, we do not require to implement or configure any complex logic; we can just start using the validation just by adding valid annotation with the object, and it will internally do the things for us. In spring boot, it will automatically do this validating part for us without implementing anything. Here we will see how it works internally and how we can start using it in our application to apply the server-side validation in our code.

Syntax of Spring Boot Validation

We can use the valid annotation on the spring boot controller class. To use this, we need to follow the basic standard given by the spring boot framework.

@RestController
class your_class {
@PostMapping("/your_end_point")
ResponseEntity<return_type> your_method(@Valid @RequestBody Your-object obj) {
// logic goes here . }
}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As you can see in the above line of syntax, we are trying to use the @Valid annotation to validate our object passes. This is quite easy to use and handle. Here, we will see what other configuration needs to be in place in more detail.

Example:

@RestController
class Demo {
@PostMapping("/test")
void test(@Valid @RequestBody Emp emp) {
// logic goes here.
}
}

From the above piece of syntax, it is clear that we just need to annotate the method and object with @Valid annotation of spring boot.

How does Validation work in Spring Boot?

As we have already known, we do not require to do lots of configuration in spring boot to validate the object at our controller level; this is also called server-side validation. For this, we can use @Valid annotation from spring boot which does all the things internally for us to validate the object in the controller itself.

Here we will see how we can use this inside our spring boot application to validate the controller’s request object.

1. Add the dependency into the pom.xml or your build.gradle.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

In order to use this annotation inside the application, we have to have this dependency in place. After adding this, we can access the various validation constraints in our entity class to validate them.

2. After adding the dependency successfully, we can now add the validation constraints in our entity class to validate the object in a request using the @Valid annotation.

Here we will see one sample piece of code to show how we can use the various validation constraints in our entity.

Example:

@Entity
@Table(name = "EMP")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
@NotBlank(message = "Employee Name is mandatory to fill !!")
private String name;
@Enumerated
@Column(name = "STATE_ID")
private State state;
@Column(name = "CITY")
@NotBlank(message = "employee city is mandatory to fill !!")
private String city;
@Column(name = "DEPARTMENT_NAME")
@NotBlank(message = "employee department Name is mandatory to fill !!")
private String departmentName;
@Column(name = "SALARY")
@NotBlank(message = "employee salary is mandatory to fill !!")
private Double salary;
}

As you can see in the above code, we have created one entity with some validation constraint name of the class is Employee, now we can validate this object using the validator provided by spring boot.

3. Now, after this, we have should have a rest controller, which is responsible for handling the HTTP request for us. Now we have to provide it with a name and a method that will handle the request and validate the object at the method level only.

Here we will see how we can do that using the @Valid annotation from the spring boot framework.

Example:

@RestController
public class EmployeeController {
@PostMapping("/validate")
ResponseEntity<String> addEmp(@Valid @RequestBody Employee emp) {
// your logic will go here ..//
}
}

As you can see in the above piece of code, we have first created a class that is annotated with @RestController, which will tell spring that it will handle the request for us. After that, we have created one method name, addEmp, responsible for adding the employee into the database. But here in this method, we have two things @Valid and @RequestBody, which will convert the json into the respective spring object for us. @Valid here first validate the object against the entity we have created, also; we have provided their validation constraints; if it works fine, then it will go to the next step to save the object; else, it will throw an exception for us.

4. Now, the last step is to create the Spring main class to start the application; this class has the same structure only; we can name it anything we want, not restricted.

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

This is the main class where the initialization of the application will start. Without this, the application will not work; here, we have to use @SpringBootApplication annotation and the main method inside this class.

Conclusion

Server-side validation is very much required to validate the object if it contains the valid values or not. It will also ensure that the object is valid and can be used for the further process or operations. It is very easy to use and handle; we just need o care of the dependency that we have add in order to use this validation in the Spring Boot framework.

Recommended Articles

This is a guide to Spring Boot Validation. Here we discuss the introduction and how validation works in spring boot? Respectively. You may also have a look at the following articles to learn more –

  1. Maven Repository Spring
  2. Spring Boot DevTools
  3. Spring AOP
  4. Spring Cloud Components
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more