Friday, May 19, 2023

How to validate HTTP POST Request 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. You can use JSR-303 Bean Validation Framework and @Valid annotation in Spring MVC to check the request data on POST request.  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
}


How to Validate POST Request Payload on Spring MVC?

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.

Here is an example of Model class which has many validations for different field like for registrationId, we have marked it not null as well minimum length must be 2. We have similar validation for firstName, lastName, and age where we have also put a list on maximum age

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 HTTP Post request payment in a controller on Spring MVC application. You can use @Valid annotation and JSOR 303 Bean validation framework and all the annotations it provides like @NotNull, @NotEmtpy, @NotBlank, @Min, @Max, @Pattern, and @Email to validate the data before you pass them down to lower layer of your application like for storing into database. 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 about validating incoming request data or payload on server side using Spring MVC 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