In our previous Spring MVC Validation with annotation tutorial, we have learned how to use JSR303 Bean Validation to validate our Spring MVC Forms. There you could see the validation messages are added on the bean constraints itself @NotEmpty(message=“FirstName cannot be empty”) but that is not the way we code in the real world situation. Messages will be added to a property file separately so that we don’t have to restart the server every time when we modify the validation message or when we add a new message. Let’s see how to do validation with ResourceBundle.
Every thing resembles the same as my previous tutorial except we need to add an entry in the SpringConfig-servlet.xml and new property file.
SpringConfig-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.jackson"></context:component-scan> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/Jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="props"></property> </bean> </beans>
In our configuration file, we have added an entry for the messageSource , which has the property basename whose value is “props” that should be the name of our property file which contains validation error messages.
props.properties
NotEmpty.rb.firstName=FirstName cannot be empty
Size.rb.firstName=Size should be between 1 to 6
NotEmpty.rb.email=Email Address cannot be empty
Email.rb.email=Please enter a valid email address
Size.rb.lastName=Size should be between 1 to 6
The property has to be framed as below.
NotEmpty . rb . firstName = FirstName cannot be empty
Constraint. ModelAttribute . Variable = Custom message
The property has 4 main parts
- Validation Constraints applied on our bean.
- ModelAttribute used in our controller.
- Variable in our bean for which we have applied the constraints
- The custom message which has to be displayed when validation errors occur.
Lets run our application
http://localhost:8080/SpringMVC_Validation/register
Leave a Reply