Session, let us learn how to perform validation using JSR 303 bean validation APA. You earlier when we were working with spring validation API, we created a class which implements validator interface. And we were adding the constraints within validate method. In this case, we are going to use annotation the annotations are added indeed domain or the model class, if it is customer or if it is employee or product, you are just going to add the annotations which are nothing but validation constraints saying that the name should not be empty using not empty annotation, the salary should not be null using not validation, then min max, what is the minimum length and what is the max what is the minimum size and maximum size and similarly, there are a few more annotations These annotations provide the validation constraints. Once annotations are added, you need to tell spring that validation has to be performed based on these validation constraints.
For this in the controller class, you have to add arsenic valid annotation before the domain object. In the previous case, we used our direct validated annotation. Together with that we also wired a validator also here that is not required, just add all the annotations or just add the annotations that are needed in the domain class. Then, where exactly you want to validate their before their domain objects, you add a third valid annotation. Of course you are going to use binding the binding the cells is a holder of the validation errors. It will check it by the way annotation errors and throw the arrows to the browser.
Again here I say we are going to work only with JSP if you are going to use any other view framework, you can capture the errors in the in that particular page and show it in the browser. In our case we will be seeing the errors only in the console. Now, let us see the annotations that are used for spring validation. I have listed out the annotation at the rate at the rate max assert true or false, not not empty, not empty is used with strings not null can be used with wrapper classes then not black sighs past future these are used with date then factor for giving password patterns and for giving a user name pattern you are using fat so we will be using the annotations from Java x validation package and Hibernate validator JPA whatever annotations you have seen few of them are some Java eight validation and few are some hibernate validator.
Now let us see an example of performing validation. Let me first list all the steps and then we will go in for the program. First create a spring starter project with weapons dependency when they add weapons dependency automatically hibernate validator API's will be added. So you don't have to add any other dependency other than web, which is an application startup. Next, you'll need to create JSP pages as usual, then create the model class. In this case, I'm going to use the employee in the employee class you have all the instance variables, you will be using annotations like not null, not empty size min max, based on your instance variables.
If you using email you can go in for accurate email all these are all these annotations are from basically from two packages one is from hibernate, other one is from Java x validation then you need to create the controller where exactly you are doing the validation there before the object you need to use accurate valid annotation. Let me show you that. So this is palm dot XML I'm using only started with then employed Java This is a model class for each and every instance variable I have added the annotation above name not empty and size above city not empty above age not null min and max. The minimum size minimum age should be greater than 21 maximum of 68 then salary for salary have not added any irritation. If you want, they can go in for a lot less then email for email and using not empty and other he made accurate email is from hibernate validation APA together that you have got past past and future.
These are also hibernate validation EPA. This is my controller class in the controller class that exactly I'm going to do the validation that I have to use accurate valid annotations before the model object in this case employee. So before the employee object I'm adding at the rate valid. So that domain model will be valid the domain objects will be validated based on the validation constraints that you have given using annotations. Once the validations are used, once the validation is completed, all the errors will be captured by this binding result. You are again checking if the result is having error, go to an EMP form dot JSP l go to success Okay.
Now, what we will do is we will go back to eclipse and we will try this validation using JSR 303 I am an eclipse I have created a spring starter project with Weber's dependency the project name is spring MVC validation. So, I have done the initial setup. So, let us just go through the application first in combat example I am having this application class then in comm dot example dot v i am having employee dot java which is the model class then in the controller I have got EMP controller application dot properties I have given the prefix and suffix that is I am controversy view resolver as usual I have got three view pages inside views folder EMP success and show from now, let me go to this model class. In the model class I have added the appropriate annotation. Let us see it one by one.
This employee class is having named city Yet salary an email of instance variables are for each and every instance variable I have added the annotation of their name about city and email I have added address not empty, it means the form fields should be filled in with value upon salary and yes, I have added at the rate not not it means it must not be null you are supposed to provide some value they are using wrapper classes here it is integer then I am trying to do the method here itself method name is required. So, for each and every property you can add the validation message in the annotation itself for not empty and just giving the message here itself. What about this one for city city also I have given city's request for email I have not given anything it means spring is going to give its own default message next advantage face min max has two things.
Here we are talking about the length. The length of name, the length of name should be at the minimum should be five maximum should be 15. Not more than that oneness enclosed in oneness exclusive, we will see what is inclusive and what is exclusive while doing the program or while you're seeing the output. Next, not accurate when an accurate map here it talks about the value that one is less This one is value, you should not be less than 21 and greater than 68. Here also oneness when one does match occurs oneness inclusive and oneness exclusive. For this as well.
If you want you can add your validation message. If you don't give the validation message spring will take care of it and it's neither a validation message automatically. Again I'm telling Here we are using only HTML form. So we will not be seeing any error messages validation message in the browser all the validation messages you can see only in the console. Now, I will come to this image for email I have given address not empty and email not empty is to check whether you have entered any value or not email checking for this pattern okay. So, this is the model class next let me come to the controller in the controller you need to go on Add at the rate valid where exactly you are performing the validation Okay.
Now, let us see the flow so that we will see that to add this annotation at the rate valid annotation to start with I have to go into the CMP controller request mapping is slash it will go in search of here I got home dot JSP now I have got show EMP form go to EMP controller slash show EMP form which is going for show form. Already we have done this program. So you can just copy paste it or you can modify the same program you have done earlier. This is short form dot JSP in short form the JSA have a form with a form fields. The model class that I have created is going to have the instance variables that are similar to the form fields. The name also matches name, age, city salary and email.
Now, I will come to the CMP controller, the request mapping is an employee What about the methods I can even have the method post. So, here I will just go into our method as post I will save it and in EMP controller what I can do, I can just go and add method equals to request method dot post I am not getting any content. The reason is here I am just giving the map path directly. If you are going to add more parameters with the way in an annotation, you need to do the name of the parameter so it has value equal to it Employee methodical to request method dot now I will do Ctrl Space I will get it post Can you see this okay this is one way one other way also let me just tell you instead of using request mapping, I am specifying the HTTP method you can go in for direct mapping, what is the meaning of it let me just show you instead of adding this line and just give slash map and now directly I can go in for post mapping within which I can just use slash employee I hope you can understand this and you're also what are some methods here it is good so, I can use directly address get mapping, similar to get mapping and post mapping your output mapping and delete mapping portfolios and you want to update a for delete can be used when you want to delete something in the backend.
When we are working with eyewitness. We will be using those now. You I can just use it directly Ctrl C ctrl v. So, this itself provides that the is this is using get method and port mapping specifies that it is using POST method. Now in our employee what we are doing we are trying to create an employee object and then we are setting the attribute to EMP it's something like records dot set attribute EMP comma employee our model dot add attribute EMP comma employee. So spring creates an object populates the value and setting it in a dummy name is EMP. Here only we are going to use at the rate valid annotation before the model object.
Okay, and I am trying to print the employee object here I am checking the cell dot hash here as I have used Slava It is always a better choice to use logger so that you will know what is actually happening in your application. You can use lava dot info Each and every method specifying in which method you was what actually the method is doing. Right now, we are trying to capture the error. So I have just used Nava dot get field error.to string. Okay, now let me try running this application. I don't need this employee statement, I will remove it, I will save it.
What about methods or properties? We don't need it because I'm not going to use it. I'm just going to show the output in console to actually teach you how exactly validation is happening. Select MVC validation, right click run as run on server. Always remember, you need to run only one application. If you are trying to deploy multiple application on the server, especially spring application.
It will take time because you're working with spring boots for each and every application it will try to run the banner there are four choices for you to offer. banner like set banner or you can just set it up off click Finish the application has started I am in home dot JSP let me click this link I am unsure from the JSP without entering any value, let me click Add employee I will open the console as I told you you cannot see any error message it will come back to the same form show from the JSP if you want to see the error messages, you need to use the appropriate view framework like sign leaf or you can use spring form tags. Now here let me just scroll up the console. Here you can see the error message we are at Nava dot era right field error an object named rejected value it is not empty we have given and name is required.
Can you see the default message it is showing over here from where am I getting the default message. I have added written employee dot java. Let me show that here. Is my employee class here I have given the messages name is required. So, this message only is pulled out and shown in the console. Now similarly let us try it out again let me try giving me age and just give it us one and I will leave the other fields click Add employee again and get better unless he as you scroll up EMP on field salary rejected value non core does not matter dot EMP dot salary and then they have got this salaries request Can you see that this is a error message that I have got an employee salaries request Okay.
Now what is happening whatever values you have entered when you are trying to validate it, even though you're entered name and city properly, all the modules are fleshed out. What if you want to have the previous values so You can modify on the existing value what it can do is you can try to retrieve the value using the EMP, what is this EMP it is the dummy name of the employee object that has the attribute name right. So with the help of that attributes you can retrieve name salary city I will just show you I need to go to the show form dot JSP here now I am going to use value equal to because it is going to come to the space already EMP is populated with value so it's just going to take the value and populate it here. I have added value for all the form fields.
Let me enter the proper form field name. Actually we are trying to retrieve the value of the domain objects using the Domini you dollar EMP is going to give you the complete details of the employee EMP dot name this expression language so it is like the dumbest name dot instance variable name that's what I have given over here. If the value is not there nothing will be printed if the value is already there it will be assigned to this particular form field value Okay. Now let us try this again let me rerun this application. Now application has started and just scroll the console to the side and I will have it let me click Show employee form. I will click Add employee and getting an error name is required.
Can you see now let me enter name ra click Add employee the pH should be between five and sorry the size should be between five and 15. The name is already retained because they we are trying to retrieve the value from EMP. Now I will just use ra me. Yes. And click Add employee salary is required now it is asking for salary. Now let me enter salary 9000 you are better norther it has taken cabbage spring framework only.
So, you are trying to re enter the news after the message click Add employee again may not be empty What does may not be empty for what actually it is coming for field error in object EMP on field email for email together with not empty we have not given any message. So, spring is giving this message may not be empty. So, for email, let me just give it as a It must not be empty. I'm not following the pattern let me click Add employee cities request is asking for city that means just give you this bamboo click Add employee may not be none for what Yes, we have not given a message so the default message is coming. So I will just add it as 20 I mean to 20 click on employee. Now it is going in for email pattern.
Can you see it is giving a pattern message not a well formed address. Here also We have not given any message. So for email, it is just giving that default messages, not a well formed email address. So here I'm going to use a add a.com Click Add employee one more is left out that is for Yeah, what is that age must be less than or equal to 68. So 68 upper hand this inclusive lower handles exclusive 21 to 68 I hope we get 68 is acceptable, but 21 is not acceptable. Now I will just going for I will just fix 21 of lacing.
So yeah, it's going to be next page 21 Let me just take it to the employee class. employee. Minimum is 21. Maximum is 68. So it's accepting both 21 and 68. So both are inclusive.
Just remember this Here I have given 21 let me just do okay I will give 21 Let me check the output click Add employee now it is going to the next page 21 is accepted and again here I'll just change it to 68 click on employee that is accepting okay and five and 15 we said right the already ramen is 56789 1011 1213 1415 Click Add employee it is accepting. Now I will add one more p add employee it will stay back on the same page. So, five between five and 15 minutes it is accepting five also 15 also both are inclusive and between 21 and 68 for minimum and Max both are inclusive okay and proper value so click Add employees it is going to EMP success dot JSP. So, this is how you pull form validation for forms in a spring MVC application using JSR 303 bean validation API