Newsletter

Spring MVC Annotation (JSR-303) Bean Validation With @Valid Example

Spring-MVC » on Aug 1, 2013 { 36 Comments } By Sivateja

Validating a (spring) bean is a mandatory thing in every IT individual project, let us see how to validate a bean in spring MVC JSR-303.  Please check this tutorial before you read this article [ https://www.java4s.com/spring-mvc/spring-mvc-annotation-jsr-303-validation-tutorial/ ].  In order to work with JSR-303 you should have validation-api-1.0.0.GA.jar,hibernate-validator-4.2.0.Final.jar in your class path. You can download these files from maven repository, dont confuse hibernate-validator-4.2.0.Final.jar is a reference implementation for JSR-303 :-).  However i provided the download links for the above jar files in the previous article.

You can do validations upto some extent with a single jar file, either validation-api-1.0.0.GA.jar or hibernate-validator-4.2.0.Final.jar  but with combination we can do better validations 🙂

Files Required

  • index.jsp
  • web.xml
  • Java4sController.java
  • java4s-servlet.xml
  • loginPage.jsp
  • UserDetails.java
  • success.jsp
  • failure.jsp
  • props.properties

Directory Structure

index.jsp

<font face="verdana" size="2">
   <a href="displayForm.html">Login..</a>
</font>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<servlet>
   <servlet-name>java4s</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
   <servlet-name>java4s</servlet-name>
   <url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Java4sController.java

package java4s;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Java4sController {    

        @RequestMapping(value="displayForm", method=RequestMethod.GET)
        public String helloWorld(UserDetails ud) {
            return "loginPage";            
        }

        @RequestMapping("/login")
        public String loginCheck(@Valid UserDetails userDetails, BindingResult result, ModelMap model) {
            if (result.hasErrors()) {
                return "loginPage";
            } else {
                model.addAttribute("lfobj", userDetails);
                return "success";
            }
        }

}

java4s-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<context:component-scan base-package="java4s" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basename" value="props" />
    </bean>

</beans>

loginPage.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
     <title>Spring3Example</title>
<style>
  .error {
      color: #EF1313;
      font-style: italic;
  }
</style>
</head>
<body>

<form:form action="login.html" commandName="userDetails">
<table>
<tr>
    <td><font face="verdana" size="2px">User</font></td>
    <td>:</td>
    <td>
    <font face="verdana" size="2">
    <form:input path="user" /> <form:errors path="user"></form:errors>
    </font>
    </td>
</tr>
<tr>
    <td><font face="verdana" size="2px">Email</font></td>
    <td>:</td>
    <td>
    <font face="verdana" size="2">
    <form:input path="email" /> <form:errors path="email"></form:errors>
    </font>
    </td>
</tr>
<tr>
    <td><font face="verdana" size="2px">Phone</font></td>
    <td>:</td>
    <td>
    <font face="verdana" size="2">
    <form:input path="phone" /> <form:errors path="phone"></form:errors>
    </font>
    </td>
</tr>
<tr>
    <td><font face="verdana" size="2px">Blog</font></td>
    <td>:</td>
    <td>
    <font face="verdana" size="2">
    <form:input path="blog" /> <form:errors path="blog"></form:errors>
    </font>
    </td>
</tr>
<tr>
    <td>
    <input type="submit" value="Submit" />
    </td>
</tr>
</table>
</form:form>
</body>
</html>

UserDetails.java

package java4s;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.URL;

public class UserDetails{

        @NotEmpty
        private String user;

        @NotEmpty
        @Email
        private String email;        

        @NotEmpty(message = "Phone should not be blank.")
        @Size(min = 10,max = 10)
        private String phone;

        @NotEmpty(message = "Enter your blog URL")
        @URL
        private String blog;

        public String getUser() {
            return user;
        }

        public void setUser(String user) {
            this.user = user;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getBlog() {
            return blog;
        }

        public void setBlog(String blog) {
            this.blog = blog;
        }

}

success.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
       table td{font-family:verdana;font-size: 12px;}
</style>
</head>

<body>
<font face="verdana" size="2">Welcome Mr. <b>${lfobj.user}</b>,<br>
Validations Success..!<br><br>
<u>You Entered</u><br>
</font>

<table>
    <tr><td>Email</td><td>${lfobj.email}</td></tr>
    <tr><td>Phone</td><td>${lfobj.phone}</td></tr>
    <tr><td>Website</td><td>${lfobj.blog}</td></tr>
</table>
</body>
</html>

failure.jsp

<html>
<font face="verdana" size="2">
<b>Login Failed..!</b><br>
    Please enter 'java4s' as user name and 'pass' as password.
</font>
</html>

props.properties

NotEmpty.userDetails.user = User Name is required
NotEmpty.userDetails.email = Email is required

Email.userDetails.email = Enter valid email Id
URL.userDetails.blog = Enter valid URL

Explanation

  • Run the application > index.jsp file will be executed
  • I am calling displayForm.html from index.jsp, so DispatcherServlet passes the request to Java4sController.java
  • In Java4sController line number 14, mapping will be verified, and helloWorld(UserDetails ud) method will be executed and it will return string value ‘loginPage‘ from that method, in other words loginPage.jsp page will be executed
  • So loginPage.jsp > line number 15, once we click on submit button ‘login.html’ action will be called
  • Again come to Java4sController.java line number  19, mapping will be verified, and flow moves to loginCheck(@valid -,-,-) method, there in the first parameter i am using @Valid annotation, and calling the bean as @Valid UserDetails userDetails
  • Now come to UserDetails.java > validations will be executed > if have any errors container adds those errors to BindingResult object [2nd parameter of loginCheck(-,-,-) method of Java4sController class ]
  • Finally check the error(s) and open either success or failure page, that’s it

Notes:

1. In Java4sController line number 15, is it necessary to take our bean class as parameter in helloWorld(UserDetails ud) ?
A] Yes we should, the reason being before we call loginPage.jsp [in line number 16 of Java4sController] we need to set the fields to their default or empty in the jsp before it loads, so i am taking UserDetails bean as parameter, so just wait….!!!! check loginPage.jsp line number 15, i have written commandName=”userDetails“,

Did you observe…?

My Bean name is UserDetails
and i took commandName in loginPage.jsp [line number 15] as userDetails

In jsp, i have taken commandName value same as my bean name but first character is lower 🙂 which is default notation while creating object in java.  So when ever we call loginPage.jsp, fields will automatically get mapped[assigned to empty or null], hope you understood my pain ;), this is very important step, there might be a chance of getting Run time exception if we ignore this step.

2. Can we write helloWorld(UserDetails ud) method of Java4sController without passing UserDetails object ?
A] Of course we can 🙂
We can change helloWorld(-) method….

@RequestMapping(value="displayForm", method=RequestMethod.GET)
        public String helloWorld(UserDetails ud) {
            return "loginPage";            
}

to

@RequestMapping(value="displayForm", method=RequestMethod.GET)
         public String helloWorld(ModelMap model) {
      UserDetails ud = new UserDetails();
       ud.setUser("");
       ud.setPass("");
      model.addAttribute("userDetails",ud);
      return "loginPage";            
}

But make sure, key in model.addAttribute(“userDetails“,ud) should match with commandName=”userDetails” in jsp, that’s it.

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

36 Responses to “Spring MVC Annotation (JSR-303) Bean Validation With @Valid Example”
  1. Sasi says:

    Please explain @RequestMapping Annotation ,the different ways it can be used,different parameters it takes.

  2. venkat says:

    i want to display UserDetails bean class user field display starting letter must be specific letter (a/A) remaining time show to error message on that time what i can do help me

  3. Karthick says:

    Hi,

    For me the validation is not happening. Whatever I give in the loginpage it directly goes to success page. I use spring 3.2.4 with maven 3.1.

  4. Jackson says:

    Hi Java4s

    The validation is not at all happening, even i have followed all the mentioned step @Valid seems to have not effect…

    Can you please help me on tat?

    Regards
    Jackson

  5. On which case we will implement @RequestMapping annotation for a class level or method level ?
    Could you please suggest me , when should i go for @ModelAttribute in my Application ?

  6. Nipun says:

    How to validate number. It accepts character in phone no.

  7. DilipKumar says:

    In Spring MVC how to download PDF file dynamically?
    in the internet all examples shown only static download….i want only dynamic download the file….plz show me this example?

  8. Guruputra K M says:

    For me a Simple Hello world example executed Successfully, but for the same this Example validation, the page is not yet all displaying (main page i.e. index.jsp) it
    some times it shows 404 error, some times it through the exception

    could you please give me Solution for this

    Regards
    Guruputra K M

  9. sriprem says:

    I too got the same error “HTTP:404 resource not found” ..do anyone can help me out of this

  10. kranthi says:

    i used the same code but when i clicked on login.. link 404 error is showing..
    how can i resolve this issuse

    Thanks Regards
    Kranthi

  11. manjunath says:

    where is displayForm.html file.And that is not mentioned in above example.

  12. Chandan Rajput says:

    @Manjunath,
    Dear friend, displayForm.html is actually not html file but it is controller mapping name, see in Java4sController.java file line 14. You can also write only displayForm without .html extension.

  13. java developer says:

    Great, Clear explanation of concepts

  14. shubam says:

    the properties setted in props file is not reflecting on my page.

  15. Raj Gopal says:

    Make this tutorial more excellent by adding password and confirm password fields to existing one ………
    http://stackoverflow.com/questions/1972933/cross-field-validation-with-hibernate-validator-jsr-303

  16. Raj Gopal says:

    I want SOAP tutorial asap .

  17. hanumantarao says:

    where is th login.html page can u …………….

  18. Pradip says:

    can u please provide me the JTable edit,udate,detete with hibernate and spring MVC

  19. vivek says:

    cool example!!!!! Worked very well for me. Just need some patience.

  20. Arun says:

    Hi,

    I downloaded the above project and executed in my machine. But i am getting the following error when I click on click link.

    Http:Status:404 ….displayForm.html not found
    Regards,
    Arun

  21. Prabakaran says:

    excellent explanation…Thanks

  22. Gouri Shankar says:

    Hi, Excellent tutorial, everything is running fine in my machine, but the props.properies values are not reflecting , why?

    please help.

  23. manoj says:

    how to add external style sheets in spring. I am facing many troubles can you please help to resolve the issue

  24. Avinash says:

    i am trying to use this code in netbeans .All things are working fine but only validation is not working . please help me out.

  25. Krish says:

    Wow, Excellent & awesome explanation with very nice code….
    Thabk u so much

  26. Krish says:

    Great Explanation..super..

  27. Akanksha says:

    Very clear and point to point explanation of each and every syntax.Thanks

  28. Hymavathi says:

    Hi

    You have done this program by using Spring MVC 3.2 but I am using Spring MVC 3.0 Can you provide all jar files for that because I am not getting output when I click on login it shows The server encountered an internal error () that prevented it from fulfilling this request

  29. kallayya says:

    Dear Friends,
    The above code has been not working in my system after click the login option its nothing show what was the problem am not getting that ,

  30. Amol Gangawane says:

    what will be the configuration for server side validation if we don't have Pojo classes in spring mvc?
    and what will be xml equivalent code for Annotations?

  31. Arun Singh says:

    Thanks,

  32. AhmedAlraz says:

    can we use spring validation without using property file

  33. Azhar says:

    Validation isn't working.
    Any help would be appreciated.

  34. saniya says:

    Sir how to link css and js folder in spring mvc in simple dynamic web project not maven project..

  35. Harish says:

    Hello Sir,

    whenever forever your tutorial is the best one. which is neatly and clearly explained why we're doing each steps. Thanks a lot.

  36. bhagyashri dhanwate sunil says:

    please sir send spring mvc crud operation.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.