Spring MVC Fast Tutorial: Form Validation

What are we going to build?

User input validation for the new car form.

Validator

This Validator class will validate a Car: 'WEB-INF/src/springmvc/validator/CarValidator.java'

package springmvc.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import springmvc.model.Car;
 
public class CarValidator implements Validator {
 
	public boolean supports(Class aClass) {
		return Car.class.equals(aClass);
	}
 
	public void validate(Object obj, Errors errors) {
		Car car = (Car) obj;
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "model", "field.required", "Required field");
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required", "Required field");
		if ( ! errors.hasFieldErrors("price")) {
			if (car.getPrice().intValue() == 0)
				errors.rejectValue("price", "not_zero", "Can't be free!");
		}		
	}
}
  • supports(): declare classes supported by this validator
  • To add an error these parameters are needed:
    • Car field name
    • error message key
    • default message if no message is not found for the key

View

Let's update the view 'jsp/carNew.jsp':

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<html>
 
<head>
  <title>New Sponsor</title>
  <style>
    .error {
    	color: red;
    }
  </style>  
</head>
 
<body>
	<h1>New Car</h1>
 
	<form:form method="post">
 
		Brand<br />
		<form:select path="brand">
		   <form:options items="${brandList}" itemLabel="name" itemValue="id" />
		</form:select>
		<br /><br />
 
		Model <form:errors path="model" cssClass="error"/><br />
		<form:input path="model"/><br /><br />
 
		Price <form:errors path="price" cssClass="error"/><br />
		<form:input path="price"/><br /><br />
 
		<input type="submit" value="Submit">
 
	</form:form>
</body>
</html>

Configuration

We now declare the validator for the URL addCar.html in 'WEB-INF/springmvc-servlet.xml'

    <bean name="/new_car.html" class="springmvc.web.CarNewController">
        <property name="commandClass" value="springmvc.model.Car"/>
        <property name="formView" value="carNew"/>
        <property name="successView" value="list_cars.html"/>
		<property name="validator">
        	<bean class="springmvc.validator.CarValidator"/>
        </property>
    </bean>

Result

Build (ant) and relaunch Tomcat: http://localhost:8180/springmvc/new_car.html

We can check it's working by entering empty values:


Previous: Form Processing --- Up: Spring Fast Tutorial --- Next: Dependency Injection

 

Feedback

this is very good way to learn Spring but please can you do this tutorials with Net beans or Eclipse? this will be a great job thank you
Mahmou Morsi
July 23, 2008
#1
You can clearly see from the screen shots in earlier sections of the tutorial that Jérôme is using Eclipse. However I think he is doing a good job of hiding it as tutorials should be generic as possible. Not everybody uses NetBeans or Eclipse.

July 24, 2008
#2
Could you please describe what supports method do ?
sain
August 28, 2008
#3
great tutorial... kudos to u..
Goodguy
September 29, 2008
#4
thnks 4 the great tutorial!!!
ariesrana
October 1, 2008
#5
Because of you, I love Spring now!
Dmitry Bahtiarov
October 10, 2008
#6
Thanks for good tutorial.
Mr.A
October 12, 2008
#7
Why don't use use spring:bind tag?
Mr.A
October 12, 2008
#8
that was simply superb
Balaji Srikanth
November 25, 2008
#9
Exactly what I was looking for!

December 26, 2008
#10
Dubakoor material
johnson
February 17, 2009
#11
No downloads for this one?
saket jha
April 6, 2009
#12
This is excellent one ,but no download..
sanu
April 13, 2009
#13
it really good site from spring beginner . but when i am using <form:form></form:form> in my jsp. i am getting no such method error. any one can help me
sumadha
April 24, 2009
#14
best tutorial for beginning with spring, that i ever seen:)
y0y0
May 4, 2009
#15
Good Tutorial..
Bals
May 12, 2009
#16
Excellent Tutorial. Simple, yet covers most of the spring functionality.
Satish
May 26, 2009
#17
Spring bind tag is old when compared to the <form:tag> and the error messages are not displayed after validation when spring tag is used.
gomsz
June 4, 2009
#18
Its really superb tutorial for starting spring. Thanks a lot..
Avi
June 7, 2009
#19
Excellent!!! easy and funtional, very good, thanks!!!!

June 12, 2009
#20
Awsome, simple and clean, thanks very much!!!
tommmy
June 15, 2009
#21
Outstanding example for validation that i never ever seen this type of easiest understanding example thanks a lot for the people who introduced this example
VUMMADI MANOHAR REDDY
June 30, 2009
#22
thanks a lot for the example... really help ful :D but i have a little doubt.. wil this validation work in a ftl? in my case it didn't :(
farhath
July 3, 2009
#23
Lucid
:-)
July 9, 2009
#24
excellent tutorial
jaks
July 20, 2009
#25
yeah tutorial to mast hai !!!!
jasminder bhomra (jassi)
July 20, 2009
#26
It's simple excellent.The way you have presented the topic is superb.

July 31, 2009
#27
good one
sg
August 11, 2009
#28
Thanks again - very handy!
PUK
September 10, 2009
#29
This is most appropriate starters tutorial i have come across on the net for any technology. Thanks a lot Jérôme
Ajay
September 11, 2009
#30
Great tutorial. Much appreciated!!!
yupi
September 14, 2009
#31
Hi, if somebody types string in the field, you will receive exception (
pete
September 16, 2009
#32
Somebody knows how to handle the Exception if you put a String in the Price Field? the exceptions is shown in the <form:errors :(
aamc
October 15, 2009
#33
what happends if I put "rrrr" in price Value?? how can i get a custom message for this error??
aamc2
October 15, 2009
#34
Hi, i've solve the problem: you have to create a messages.properties file with: typeMismatch=invalid field typeMismatch.int=This value have to be integer typeMismatch.java.lang.Integer={0} have to be Integer. typeMismatch.java.util.Date={0} have to be Date, use format MM/dd/yyyy. and then map this in your application-context.xml with: messages That's all
aamc2
October 18, 2009
#35
I find framework in PHP...and fell in love with CodeIgnitor. I find framework in Java.. and fell in love with Spring. Thanks dude...
MSHW
October 25, 2009
#36
Great Tutorial. Quite Easy to understand and learn Spring. Many Thanks for your help in letting me grasp spring fundamentals in such a short time.
Praveen
November 10, 2009
#37
Really fantastic tutorial
rahul jain
December 22, 2009
#38
Is there a way to remove the added errors from the Errors object
kishore
December 28, 2009
#39
Hi, I'm adding all the field validation errors as follows errors.rejectValue(fieldName, errorCode) once i add the error based on some logic i want to remove the corresponding error from the 'errors'. How can i remove an added error from the errors object. I searched and not found any remove method on errors to remove the same. Can any one please help on this.
kishore
December 28, 2009
#40
nice tutorial. I liked it very much.
Ove
December 29, 2009
#41
Excellent Tutorial. Thank you
Venkata Madana
December 31, 2009
#42
Good stuff!
Anders Thøgersen
January 19, 2010
#43
Nice tutorial
siva
January 21, 2010
#44
xml is not valid. tag is not closed. Is it supposed to contain tag ?
Mircea
January 22, 2010
#45
Damn filterring.. I was talking about tag: lt property name eq "validator"

January 22, 2010
#46
Why is it new_car.html when the created page is jsp i.e.,carNew.jsp (http://localhost:8180/springmvc/new_car.html)
Deepa Revankar
January 29, 2010
#47
Very good material for beginers
Bhabatosh
February 2, 2010
#48
very pleased, thanks and keep going
yousef - opensoft
February 3, 2010
#49
Great simple tutorial for spring that leaves out all the other complex frameworks(eclipse,netbeans,maven,ant) that only confuse when learning. Thanks!
Kelvin
February 4, 2010
#50
Very Good tutorial! Thanks for sharing.
Rahul
March 13, 2010
#51
thanks lot of
Mugiwara
March 13, 2010
#52
This tutorial is awesome. short, strait, concise and covers basic features of spring. thanks a lot for your time, and whatever you are sharing with us.
Pascal
March 21, 2010
#53
Good tutorial

But what if the error gets generated? How will spring know to display back the form where the error occurred. Where the form link gets stored?

Please explain this concept
Raghav
March 23, 2010
#54
Nice tutorial, thanks.
In the JSP carNew.jsp, I get exception below. However If I
remove the &lt;form:errors and &lt;form:input and change it to &lt;input type="text" name="model" value="" /&gt;, then I don't get the exception.

My guess is some problem with spring tag library.

PS: I've followed the exact steps in the tutorial, using spring-framework-2.5.5.


exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /jsp/carNew.jsp at line 26

23: &lt;/form:select&gt;
24: <br /><br />
25:
26: Model &lt;form:errors path="model" cssClass="error"/&gt;&lt;br />
27: &lt;form:input path="model"/&gt;&lt;br /><br />
28:
29: Price &lt;form:errors path="price" cssClass="error"/&gt;&lt;br />


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
org.apache.jasper.servlet.JspServlet.serviceJspFile&#40;JspServlet.java:342&#41;
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:269)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:301)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
java.security.AccessController.doPrivileged(Native Method)
java.security.AccessController.doPrivileged(Native Method)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:269)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:301)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)

root cause

java.security.AccessControlException: access denied (java.lang.RuntimePermission getClassLoader)
java.security.AccessControlContext.checkPermission(AccessControlContext.java:342)
java.security.AccessController.checkPermission(AccessController.java:553)
java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
java.lang.ClassLoader.getSystemClassLoader(ClassLoader.java:1291)
org.springframework.beans.BeanUtils.findEditorByConvention(BeanUtils.java:368)
org.springframework.validation.AbstractPropertyBindingResult.getCustomEditor(AbstractPropertyBindingResult.java:110)
org.springframework.validation.AbstractPropertyBindingResult.formatFieldValue(AbstractPropertyBindingResult.java:87)
org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:230)
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:172)
org.springframework.web.servlet.tags.form.ErrorsTag.shouldRender(ErrorsTag.java:137)
org.springframework.web.servlet.tags.form.AbstractHtmlElementBodyTag.writeTagContent(AbstractHtmlElementBodyTag.java:46)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:90)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:77)
org.apache.jsp.jsp.carNew_jsp._jspService(carNew_jsp.java:118)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile&#40;JspServlet.java:342&#41;
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:269)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:301)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
java.security.AccessController.doPrivileged(Native Method)
java.security.AccessController.doPrivileged(Native Method)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:269)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:301)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)

Antony
April 23, 2010
#55
Was a local problem of tomcat on Ubuntu (issue with TOMCAT6_SECURITY variable explained at http://serverfault.com/questions/124004/tomcat-6-access-control-exception)
Once I set the TOMCAT6_SECURITY to no from yes, form:input worked fine.
Antony
April 28, 2010
#56
Bien présenté dis donc! Reste qu'il manque le fichier avec les différents messages d'erreur. Tu as précisé les messages d'erreur par défaut, mais faudrait avoir les messages d'erreur par langue :)

irnbru
April 28, 2010
#57
Thanks a lot
Elio
May 9, 2010
#58
Very Good tutorial
This is very great job.
Ramk
May 17, 2010
#59
Nice!
derp
May 24, 2010
#60
Great tutorial! God bless you!
Stefan
June 9, 2010
#61
For ecclipse please import the download content in ecclipse and everything will work or create a new web projects and place contents .

and yes esxcellent tutorial
dp
June 18, 2010
#62
I owe a lot to this tutorial. I use it as a reference and return to it from time to time. Great job man. Really appreciated.
John Barry
June 29, 2010
#63
This is really a nice tutorial for Spring learners.Thank you.
Ajay Pinnaka
July 20, 2010
#64
Please show us controller. Thanks.
Vitaly
July 26, 2010
#65
The JavaServer Faces best than Spring !!!
Joe
July 29, 2010
#66
Thanx
akAsh
August 2, 2010
#67
Really excellent tutorials!!! These are what I was looking for!
Thanks very much.

August 4, 2010
#68
nice job :)
Niko "cute" Edralin
August 25, 2010
#69
I would recommend this tutorial series to all my friends...
Nuwan Chamara
September 4, 2010
#70
not working....
ishan
September 20, 2010
#71
Hi,

This tutorial and examples are too good for a novice who is willing learn spring. I bet the person will surely benefited from this. Thanks buddy. God bless you.

Ankit Mishra
October 1, 2010
#72
Hi Thanks.. All the best
Sudarshan
October 2, 2010
#73
Its good.
N. Rahul
October 6, 2010
#74
Very Nice.

Spring becomes simple wit you.:)
Thanks
blaise
October 6, 2010
#75
very good one!
pjl
October 21, 2010
#76
short and best tutorial .
long and waste comments
wellwisher
October 29, 2010
#77
One of the finest tutorials .. I have read thank you very much.....
Sam
November 12, 2010
#78
Good tutorial but the error messages are displayed even when the page is loaded for the first time.. Thats very disheartening :-(
Disheartened Guy
November 14, 2010
#79
Really nice and helpful. Thanks
Muhammad Haider
November 16, 2010
#80
A wonderful tutorial for beginners who are all interested to learn Spring.
Abinesh
November 25, 2010
#81
perfect for beginners .
ratheesh
November 29, 2010
#82
Hello

Does anyone succeed in colorating input field when they are in error ? (not adding message)
Julien
December 3, 2010
#83
The simplicity makes this tutorial very effective and interesting. Thanks a LOT. This helped me a LOT and saved my time.
Spring MVC Amature
December 24, 2010
#84
Perfect!! loved it1

January 26, 2011
#85
Thanks good tuts
Avin
January 27, 2011
#86
Spring na enna ?
Dubagar
January 30, 2011
#87
Please give an example via eclipse , which would be more useful for freshers in developing field :)
Veera
January 31, 2011
#88
thanks its good

February 22, 2011
#89
h
a
February 28, 2011
#90
This simple but not good

March 4, 2011
#91
it is very poor code
subbu
March 8, 2011
#92
its not complete not working
Rajeev
March 10, 2011
#93
Completely impressive ... thanks !
rajendra singh jadon
April 27, 2011
#94
good source for starters in spring...but no downloads
Naveen
May 16, 2011
#95
nice tutotrial. Thank u very much,
Arjun
May 18, 2011
#96
can any one provide xml file
sathish
June 13, 2011
#97
Really very good tutorial for beginners.
Thanks
Vijay
June 13, 2011
#98
Good one
Sam
July 8, 2011
#99
supports() why would we need it???
Hung
July 19, 2011
#100
Cutting and pasting that does not work in MVC3. To get the extension to work, I had to create a class file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace incMvcSite.Classes {
public static class HtmlPrefixScopeExtensions {
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) {
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}

private class HtmlFieldPrefixScope : IDisposable {
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;

public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) {
this.templateInfo = templateInfo;

previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}

public void Dispose() {
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
}
In the Razor (.cshtml) file, I added the following:
@using incMvcSite.Classes
@using(Html.BeginHtmlFieldPrefixScope("Permission")) {

Permission

// The Html.EditorFor's would go here...

}
Notice the using to bring me extension class into scope. That allows the second using line to work.
Now the problem is that when posting back, the object is not updated. In my controller, I used a second parameter to specify my prefix:
TryUpdateModel(modelUser.Permission, "Permission");
This added the prefix to all field in the HTML, and the TryUpdateModel loaded the object with prefixed control names. Now you can properly namespace your controls for embedded edit lists, and for partial views of models with the same property names.

Shawn Zernik
Internetwork Consulting
Shawn Zernik
August 2, 2011
#101
Please, write more tutorial... You writing style is very much easy to understand for me...Thank you very much...
Maruf Hassan
August 18, 2011
#102
this tutorial is very easy to understand and very useful.....thank you for your job
terry
September 6, 2011
#103
very good example
Mahesh
September 20, 2011
#104
Nice blog. very informative.
venugopal
September 21, 2011
#105
very very usefull for starter..
Raj
September 22, 2011
#106
En los metodos supports y validate, pueden colocar un @overrice para que sobreescriba los metodos de la implementación.

ninja.aoshi@gmail.com
Itachi, ninja.aoshi
November 14, 2011
#107
The best tutorial to get Started.
Anubrata
December 7, 2011
#108
BEST TUTORIAL EVER
vineet
January 11, 2012
#109
Best tutorial
ambaye64
March 1, 2012
#110
New to Spring.. this really give me a clear picture abt this framework =) thumbs up
KacangBlue
March 22, 2012
#111
I have a question. How to restore the user input values after validation?
I have a dropdown-option A,B. A textbox(required) should appear on selecting B. So I select B and no input in text-box and click submit.

I have a validation like the given example for the text-box but i have to select option B to view the error message

Any ideas?
jackdaws
March 26, 2012
#112
Nice article
pradeep ojha
April 27, 2012
#113
This is very helpful to understand and practice spring MVC examples. Its a very good tutorial for beginners. Thanks for the examples.
Arpita Hubli
May 2, 2012
#114