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 [ ].  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
  • java4s-servlet.xml
  • loginPage.jsp
  • success.jsp
  • failure.jsp

Directory Structure


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


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.4">



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;

public class Java4sController {    

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

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



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<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 id="messageSource" class="">
       <property name="basename" value="props" />



<%@ taglib prefix="form" uri=""%>

  .error {
      color: #EF1313;
      font-style: italic;

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

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{

        private String user;

        private String email;        

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

        @NotEmpty(message = "Enter your blog 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) {
   = email;

        public String getPhone() {
            return phone;

        public void setPhone(String phone) {
   = phone;

        public String getBlog() {
            return blog;

        public void setBlog(String blog) {
   = blog;



<%@ taglib prefix="form" uri=""%>
       table td{font-family:verdana;font-size: 12px;}

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



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

NotEmpty.userDetails.user = User Name is required = Email is required = Enter valid email Id = Enter valid URL


  • Run the application > index.jsp file will be executed
  • I am calling displayForm.html from index.jsp, so DispatcherServlet passes the request to
  • 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 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 > 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


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";            


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

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



You Might Also Like

  ::. About the 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.


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:


    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?


  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

    Guruputra K M

  9. sriprem says:

    I too got the same error “HTTP:404 resource not found” 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

  11. manjunath says:

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

  12. Chandan Rajput says:

    Dear friend, displayForm.html is actually not html file but it is controller mapping name, see in 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 ………

  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:


    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

  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:


    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:


  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.


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.