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