Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

How to validate incoming payload on Spring MVC controller? Example Tutorial

Hello guys, if you are wondering how to validate incoming request payload in Spring MVC based Java web application then you have come to the right place. Earlier, I have sharebest Spring MVC courses for Java developers and In this tutorial, we are going to discuss how to validate incoming payloads on the Spring MVC controller which is also can be defined as validating the request body in the RESTful web services. So first let's have a look at validating the request body in the RESTful web services. Think you have a JSON post request and you are going to consume it. There should be a validation to this post request as the requested input will be zero or in a not accepted format.

The JSON post request is given below.

http://localhost:5000/school/api
{
"registration_id" : "IT17092540",
"firstName" : "James",
"lastName" : "Robert",
"age": 3
}


In the given POST request, you need to validate the registration_id is correctly formatted and other values are not null.


@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @PostMapping("/student-registration")
    public @ResponseBody Student register(@Valid 
               @RequestBody Student student) {
        Student student = new Student();
        student.setRegistrationId("IT17092548");
        student.setFirstName("Robert");
        student.setLastName("William");
        student.setAge(21);
        return student;
    }
}



In there, @Valid is responsible for validating the information received and @RequestBody will be used to map the requested information into the model class.


Dependency Required
Add the following dependency to your pom.xml file
.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>


Then add the configuration properties to the application.properties file:

server.error.include-message=always
server.error.include-binding-errors=always




Validation Constraints
There are many validation constraints available on Spring MVC and we are going to use only few constraints in order to validate the input. Some of the constraints are given below.

@NotNull
@Email
@Size(min=8, message="Student registration id should be greater than 8")
@Size(min=8, max=10, 
message="Student registration id should be greater than 8 or equal and lesser than 10")



Student Modal class with validation constraints.


import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Student {

    @NotNull(message = "Registration Id cannot be missing or empty")
    @Size(min = 2, message = "Registration Id must not be less than 2 characters")
    private String registrationId;

    @NotNull(message = "First name cannot be missing or empty")
    @Size(min = 2, message = "First name must not be less than 2 characters")
    private String firstName;

    @NotNull(message = "Last name cannot be missing or empty")
    @Size(min = 2, message = "Last name must not be less than 2 characters")
    private String lastName;

    @NotNull(message = "age cannot be missing or empty")
    @Size(min = 10, max = 30,
        message = "Student age must be greater than or equal to 10 and lesser than 30")
    private int age;

    public String getRegistrationId() {
        return registrationId;
    }

    public void setRegistrationId(String registrationId) {
        this.registrationId = registrationId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


If the incoming POST request is failed to satisfy the above requirements in the student modal class,
there will be 400 bad HTTP response will be sent to the client. So, the client must be prepared to handle the bad response and correct the message accordingly. 

How to validate incoming payload on Spring MVC controller?



Now that you know how to validate incoming payload in Spring MVC application, here are common validation types which every Spring MVC and Java Developer should know
  • @NotNull: field can not be null.
  • @NotEmpty: list field can not be empty.
  • @NotBlank: String field can not be empty and must behave at least one character.
  • @Min and @Max: the value must be in a certain range
  • @Pattern: matches a certain regular expression
  • @Email: must have a valid email address.

That's all about how to validate incoming message in a controller on Spring MVC application. I hope this tutorial was helpful to you and We went through all of the primary validation elements we would require while constructing an application using Spring Boot in this lesson.

Other Spring MVC articles and Tutorials you may like
Thanks a lot for reading this article so far. If you like this Java and Spring MVC tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you want to learn the Spring Boot framework from scratch and look for some of the best online resources, you can also check out these best Spring courses for Java developersThis article contains the best Udemy and Pluralsight courses to learn Spring Boot from scratch.             

No comments :

Post a Comment