In this session, let us learn how to perform validation for form in a spring MVC application. form validation and spring can be done in two ways, using spring validation APA and JSR 303 bean validation API to start with in this particular session, let us learn how to use spring validation JPA spring validation APA has got validator interface to validate objects. This validator interface works with years object, that is, whenever validation has happened has happened. All the validation errors are passed to the error object so that the error messages can be shown to the user in the browser. This spring does this in the backend when you have form in a spring MVC application, you need to have a Java class with the form fields as instance variables. This is called as a domain class or a model class.
Basically, it is a simple Java bean spring uses a data binding to bind the form fields values to the instance variables of the domain class. Then it validates the how actually the validation is done based on the validation details that you are giving in the class that implements validator interface. That is, you need to create a class which implements validator interface, wherein you will be specifying the validation details name is required city is required it should be greater than 24 numbers should be obtained digits, all these kinds of validation details you will be giving in that class which implements this validator interface based on the now the validation done by spring framework, it will capture the validation error send it to all your objects, they are an object is going to capture the error messages and throw it in the browser for you. So now, let me just show you the methods that are in validator interface support and validate method subspaces just to check whether this class is going to validate the appropriate object.
When you're passing a customer object to your customer validator, you need to check whether the object that is coming in is of type customer. If you are passing an employee object to an employee validated, you need to check whether the object is of type employee class for that only we are using supports. Next is validate. This validate takes two parameters, object and object the object that is coming in to this validator for validation errors. The result of validation to capture all the validation errors within this validate method only you will be giving all the validation details for giving the validation details are forgiving the validation conditions you are you going to use two helper classes yours add validation utils these are having few methods with the help of which you will be giving the validation condition. Let me show you with an example.
These are the things which which we are going to work with few JSP classes the domain of the model classes customer, the validator classes customer validator properties methods your start properties is to give you error messages with a name value pair, then customer controller. Now, let us see what is there in customer validator that Java This is a class which implements validator woven support and validate method. Within validate method I'm using the method of validation util rejected empty or whitespace. What is the first parameter, the second parameter is the field name. The third parameter is t error message name, method to start properties is going to have a error message and a value the message name is given here for this error message you need to give a value in messages dot properties, let me just show you that but here, it is not required is the name ID is required to see value.
Similarly, you will be doing for each and every form field. Here I have done it for customer ID, then name then city, checking whether they are empty. Next I want to check in for more condition. If the age is less than 20 or greater than 80. I want to throw an error message that is possible and again Here I'm just checking if the customer ID is less than zero then throw an error message. I will explain this in detail while doing the program.
Just understand this you need to create a class which implements validators and do the validation conditions inside validate method. All these error messages whatever you have given should be given proper value in messages dot properties file. How this name value pair will be identified for that spring uses few classes that is message code resolve default message code resolver. We don't have to bother about it, we don't have to create been further because we are working with Spring Boot, we need to add just one line in application dot properties file. In this file, you need to use the properties name. This properties name is messages underscore E and dot properties are you can just create editors' messages dot properties, which is a default properties for resource bundle.
So that one and giving over here spring dot messages dot based naming goto messages, automatically Spring Boot will go in search of the properties file to retrieve the value for the corresponding error message. Once you've done everything you need to add the validator to the controller class. This is my controller class in the controller controller class. I'm also wearing the validator, can you see private validator validator together with that I have used quantifier. Why? Because validator is an interface.
There are many classes which implement this validator interface. You have created your own class, which has customer validator. So you need to specify going first of this particular validator to validate the customer object. I We are using a direct edit binder method that is annotated with accurate in a binder, it is used to bind the validator to the controller, you can see inject the validator that we have done using at the rate or avoid then bind the validator to the controller using a thread in it binders, how this customer object will be validated using accurate validated annotation that is added before the customer object Can you see the next day was binding the search also what is this binding result binding results will check in for basic errors instead of end fairy entering a string in that case is there is an error it will capture it So, for that only we are using binding.
Now in this case it will check in for all the validation errors and it will capture it if there are no errors it will go to final success dot JSP if there are errors it will stay back in add customer form that JSP now, we will go back to eclipse and We will try an example of performing validation I am in Eclipse I have created a spring starter project and I have done the initial steps. First let us go through the application as usual I have got an application class which extends Spring Boot servlet initializer then I have got a domain class customer with name city age and customer IDs instance variable then a controller class the controller class the route mapping is it has to go to Home dot JSP let me go to Home dot JSP in home dot JSP I'm having a link show customer form again go to the controller this which is having request mapping slash show customer form.
Here I am trying to go back to customer form dot JSP this one within which I'm having a form and I have an added I mean that says Add customer again go to customer controller wear an eye over smash it Customer okay now here I have use binding result and checking if result is having errors go to show customer form, it will check in further basic errors. I have also created the validator Class A customer validator which implements validator. Before that let us try running this application without any validation, right click run as run on server. Click Finish the application has started I am in home dot JSP let me click this link. Now I am in show customer form dot JSP. If I don't enter any value for age and customer ID, the EMP value is taken to the backend that is to customer controller you cannot convert empty string into an event.
In this scenario it is a number format exception. So it is captured by binding the cell it will stay back in the same page only resells dot Hospira will stay back in the same page. Let me just show that and clicking Add customer it is saying back in the same page. Now, let me do proper values name customer ID 989 City up some value add customer it is going properly to Sephora dot JSP so that the five binding result is checking in for values that cannot be converted from string into number those kind of initial validation is take taken care by binding the cells. If you want to add your own validation you need to go in for a class which implements validator I have created the class customer validator Java which is inside validators package always you must have proper packages for proper classes. The class is annotated with at the rate conference so that spring can create an object for this class.
Here I have overridden support and validate method supports this just to check whether the option That's coming in for validation belongs to that particular class only here we are checking in for that domain object in our case at this customer and checking whether the object that is entering it is of type customer next invalidate first check this one validation utils dot rejects if empty or whitespace if the form field is empty or whitespace then it should be rejected that added two validation errors the errors is coming from here okay. And the second parameter is the field name the third parameter ID dot request this is configured in messages dot properties. So, first one is yours The second one is your instance variable name The third one is the name of messages dot properties. Already I have got messages dot properties which is created inside SRC main resources that we will open that see ID dot request.
Similarly, I have done Name name dot request city dot request. Can you see this same way name dot required and city dot request. Now if we want to go in for more validation that is and checking in for the customer ID, the customer ID is less than or equal to zero that scenario, reject the value for this we are using errors, errors that reject value. What is the first one the field name, the second one is the property name, which should be added to messages properties. The third one is the placeholder. I'll explain what is placeholders.
The last one is the default message if you have not added this particular property in the properties file, this message will be shown to the user here in my properties file. Specifically I have not added that if I have added that I have got curly brace zero and curly brace Nice one, right. So for these the buyer or the seller These are basically placeholders you need to give value the value is available here ID is for zero customer ID is for one, automatically it will be replaced. Now, similarly, I've got four gauge if age is less than 20 or greater than 80, then field name the property name, the placeholder value, if the property is not given the default value message okay. So, this is completed. Now, I have shown you messages start properties also are these are our application specific error messages, these are the types mismatch errors that occur because, yes string cannot be converted into yen, yen cannot be converted into double if you are having many exceptions like that, those will be taken care of, right.
Okay. Now in applications or properties I have also configured DMS messages dot properties file for this is completed next week. Going into the controller class in the controller class only we need to auto wire validator validator validator when you use auto wired you need to have one instance which implements validators, but there are many classes which implements validators. So, we are going in for address qualifier within which we need to be named water we will be named here it is customer validator. So, the bean name will be in camel case, let me copy this here I will come and add it over here. Customer validator Next I need to create a method that is annotated with our grid it is bind and bind the validator to customer controller.
So, let me add that public wide unit binder The data binder binder dot set validator and pass validators parameters, this method should be annotated with a direct unit binder Okay. Now, how does the domain object will be validated for that you need to add accurate validated annotation because we are added to saturate validated annotation, automatically this objects customer object will be validated, if there are any validation errors that will be captured by the binding result and it will be drawn to this particular JSP page in our case it is show customer form dot JSP. What is the view framework we are using we are going in for simple JSP only and the form is of type HTML. If you want to see the error messages, either you have to go in for spring forms that are you can go in for any other view framework like pine leaf In that case because because we are using HTML form, you will not be seeing the error messages displayed in the browser.
But you can see it in the console for getting it in the console. I am going to use logger. So let me add the logger. Already we have learned about logger, the default logger for spring framework. log back it is automatically added so we don't have to bother about it just we need to import it in this particular class. logger factory.
Logger factory should be imported only from SL for j logger factory dot get logger within Mitch parser class name customer controller dot class ended with a semicolon save it again name it a beating logger and logger factory should be from SL for j only. Now here inside this I want to see what are the errors. So inside this if condition logger dot Yara, I need to get the result error messages right. So result dot get an error already we are seen. I'm going to go in first field error. It is not of type string, but Nava dot error takes only string.
So I need to convert it to string saved before running the application. Let us do a quick recap first pages home dot JSP from home dot JSP to come to customer controller, again back to show customer form. When you enter the values it'll enter into customer controller, you are given accurate validated annotations. So it is checked which validator is bound to this current customer controller. It is called the corresponding validator class wherein it is getting validated for the time you have added the error messages. There are messages are added properly in messages stored properties and also configured in application data.
Properties files all these will be taken care of by spring framework in the backend if there are errors it will be captured by the binding the binding result is a holder of validation errors, you are checking whether errors are available if they are after that show the errors in the console and stay back in the same page. Now, let me run the application the application has started I am in the first page home dot JSP let me click this link. This is show customer form dot JSP let me click Add customer validation errors have occurred. So automatically it is coming back to the same show customer form dot JSP page. Let me just open the console and maximize the console. We have used logger dot error so it is just going to show me the error field error and object customer on field eh waters.
Yes, it is upside in because we have not given any money. Knew it is going as a string string cannot be converted into in int automatically. So it is throwing number format exception. So, this is a basic error. Now I will go in for my own custom error for customer ID and a complaint just going to add one let me click Add customer again it is staying back on the same page and maximize console. Now, let us see what errors we have got.
Name is request Can you see default message is not given, but we have got name dot request. Can you see this one right because we have not entered your name it has given me an error. Now what I will do I will enter proper name for customer ID let me give a negative value and I will click Add customers. Again staying back on the same page and go here maximize console. Oprah Okay, the first thing always remember you need to do value for customers. And even if it is going to be an improper value not an issue you just added or as you will be getting always thing cannot be converted into yet.
So for name I'll give raw customer ID minus 90. And for age nine, click on customers. Again it is saying back in the same page, I'll maximize console. Here feel the error in customer, customer ID is negative. We don't have a proper message in messages dot properties. So we are getting a default message.
Did you see that Id can be negative where it is gone. Yes, I the default messages, it can be negative from where it is coming it is coming from the customer validator. Id can't be negative. Now again and go back here. Let me add proper values for name. Customer ID is proper value nine, age should not be greater than 80.
So I'll give it us 90. Then si p p o p, click Add customers. It is again saying on the same page and Maximus console, your age is not matching. That is the default message that we add eh got match, I will just check it out in messages dot properties. I've got a dot match and I will go to customer validators, the default messages, your age is not matched, we can configure the age that matching messages start properties. Now let me go back to the browser now I will add proper values.
Name, customer ID, it should be greater than 20 less than 80. Then city let me click Add customer it has to go to the final page final dot JSP. So this is a final dot JSP page. It will open that final dot JSP page and show you the output. Here I'm trying to print success and dollar customer. So that is output that we have got over here.
This results you perform validation for forms using spring validation EPA. In the next session, let us learn how to validate forms in a spring MVC application using JSR 303 bean validation EPA Thank you