When we accept user inputs in any web application, it becomes necessary to validate them. We can validate the user input at the client-side using JavaScript but it’s also necessary to validate them at server side to make sure we are processing valid data in case the user has javascript disabled.
Spring MVC Framework supports JSR-303 specs by default and all we need is to add JSR-303 and it’s implementation dependencies in Spring MVC application. Spring also provides @Validator
annotation and BindingResult
class through which we can get the errors raised by Validator implementation in the controller request handler method. We can create our custom validator implementations in two ways - the first one is to create an annotation that confirms to the JSR-303 specs and implement its Validator class. Second approach is to implement the org.springframework.validation.Validator
interface and add set it as validator in the Controller class using @InitBinder
annotation. Let’s create a simple Spring MVC project in Spring Tool Suite where we will use JSR-303 specs with it’s implementation artifact hibernate-validator. We will use annotation based form validation and create our own custom validator based on JSR-303 specs standards. We will also create our own custom validator class by implementing Validator
interface and use it in one of the controller handler methods. Our final project looks like below image. Let’s look at each of the components one by one.
Our final pom.xml file looks like below. Apart from standard Spring MVC artifacts, we have validation-api and hibernate-validator dependencies in the project.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev</groupId>
<artifactId>spring</artifactId>
<name>SpringFormValidation</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.0.2.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
</properties>
<dependencies>
<!-- Form Validation using Annotations -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
When you create a Spring MVC project from STS, it creates two context configuration files. I have cleaned it up a bit and have only one spring bean configuration file. My final web.xml file looks like below.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Usually we look into spring wirings at the last, but this time we don’t have much configurations in the spring bean configuration file. Our final spring.xml file looks like below.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="employeeValidator" class="com.journaldev.spring.form.validator.EmployeeFormValidator" />
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="classpath:message" />
<beans:property name="defaultEncoding" value="UTF-8" />
</beans:bean>
<context:component-scan base-package="com.journaldev.spring" />
</beans:beans>
The only important point to note are employeeValidator
bean that we will inject into one of the controller and messageSource
bean to read the localized data from resource bundles. Rest of the part is to support annotations, view resolvers and providing package to scan for Controller classes and other components.
We have two model classes in this project - the first one where we will use JSR-303 annotation and our custom annotation-based validator and second one where we will use only our Validator implementation. Customer.java code:
package com.journaldev.spring.form.model;
import java.util.Date;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import com.journaldev.spring.form.validator.Phone;
public class Customer {
@Size(min=2, max=30)
private String name;
@NotEmpty @Email
private String email;
@NotNull @Min(18) @Max(100)
private Integer age;
@NotNull
private Gender gender;
@DateTimeFormat(pattern="MM/dd/yyyy")
@NotNull @Past
private Date birthday;
@Phone
private String phone;
public enum Gender {
MALE, FEMALE
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Notice that we are using @Email, @NotEmpty and @DateTimeFormat annotations that are additional to JSR-303 and provided by the Hibernate validator implementation. Some of the JSR-303 annotations that we are using are @Size, @NotNull, etc. @Phone annotation used is our custom implementation based on JSR-303 specs, we will look into it in the next section. Employee.java code:
package com.journaldev.spring.form.model;
public class Employee {
private int id;
private String name;
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
The Employee is a standard java bean and we will use our custom Validator implementation to validate the form with Employee bean.
Phone.java code:
package com.journaldev.spring.form.validator;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = PhoneValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Most of the part is boilerplate code to confirm with JSR-303 specs. The most important part is @Constraint annotation where we provide the class that will be used for validation i.e PhoneValidator
. PhoneValidator.java code:
package com.journaldev.spring.form.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneValidator implements ConstraintValidator<Phone, String> {
@Override
public void initialize(Phone paramA) {
}
@Override
public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
if(phoneNo == null){
return false;
}
//validate phone numbers of format "1234567890"
if (phoneNo.matches("\\d{10}")) return true;
//validating phone number with -, . or spaces
else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
//validating phone number with extension length from 3 to 5
else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
//validating phone number where area code is in braces ()
else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
//return false if nothing matches the input
else return false;
}
}
Our JSR-303 specs validator implementation should implement javax.validation.ConstraintValidator
interface. If we are using some resource such as DataSource, we can initialize them in the initialize()
method. The validation method is isValid
and it returns true if data is valid else it should return false. If you are new to regular expressions, you can read more about it at Java Regular Expressions Tutorial. EmployeeFormValidator.java class code:
package com.journaldev.spring.form.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.journaldev.spring.form.model.Employee;
public class EmployeeFormValidator implements Validator {
//which objects can be validated by this validator
@Override
public boolean supports(Class<?> paramClass) {
return Employee.class.equals(paramClass);
}
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required");
Employee emp = (Employee) obj;
if(emp.getId() <=0){
errors.rejectValue("id", "negativeValue", new Object[]{"'id'"}, "id can't be negative");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required");
}
}
EmployeeFormValidator is the validator implementation that is specific to Spring Framework. supports()
method implementation by Spring Framework to know objects on which this validation can be used. We implement validate()
method and add errors if any field validation fails. Spring provides org.springframework.validation.ValidationUtils
utility class for basic validations such as null or empty. Once this method returns, spring framework binds the Errors object to the BindingResult object that we use in our controller handler method. Notice that ValidationUtils.rejectIfEmptyOrWhitespace()
last argument takes the key name for message resources. This way we can provide localized error messages to the user. For more information about i18n in Spring, read Spring i18n Example.
We have two controller classes, one for annotation-based form validation and another for our custom validator. CustomerController.java class code:
package com.journaldev.spring.form.controllers;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.form.model.Customer;
@Controller
public class CustomerController {
private static final Logger logger = LoggerFactory
.getLogger(CustomerController.class);
private Map<String, Customer> customers = null;
public CustomerController(){
customers = new HashMap<String, Customer>();
}
@RequestMapping(value = "/cust/save", method = RequestMethod.GET)
public String saveCustomerPage(Model model) {
logger.info("Returning custSave.jsp page");
model.addAttribute("customer", new Customer());
return "custSave";
}
@RequestMapping(value = "/cust/save.do", method = RequestMethod.POST)
public String saveCustomerAction(
@Valid Customer customer,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning custSave.jsp page");
return "custSave";
}
logger.info("Returning custSaveSuccess.jsp page");
model.addAttribute("customer", customer);
customers.put(customer.getEmail(), customer);
return "custSaveSuccess";
}
}
When we use annotation-based form validation, we just need to make little changes in our controller handler method implementation to get it working. First, we need to annotate model object that we want to validate with @Valid
annotation. Then we need to have BindingResult argument in the method, spring takes care of populating it with error messages. The handler method logic is very simple, if there are any errors we are responding with the same page or else we are redirecting the user to the success page. Another important point to note is that we are adding “customer” attribute to the model, this is necessary to let Spring framework know which model object to use in the form page. If we won’t do it, object binding to form data will not take place and our form validation will not work. EmployeeController.java class code:
package com.journaldev.spring.form.controllers;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.form.model.Employee;
@Controller
public class EmployeeController {
private static final Logger logger = LoggerFactory
.getLogger(EmployeeController.class);
private Map<Integer, Employee> emps = null;
@Autowired
@Qualifier("employeeValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
public EmployeeController() {
emps = new HashMap<Integer, Employee>();
}
@ModelAttribute("employee")
public Employee createEmployeeModel() {
// ModelAttribute value should be same as used in the empSave.jsp
return new Employee();
}
@RequestMapping(value = "/emp/save", method = RequestMethod.GET)
public String saveEmployeePage(Model model) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
@RequestMapping(value = "/emp/save.do", method = RequestMethod.POST)
public String saveEmployeeAction(
@ModelAttribute("employee") @Validated Employee employee,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
logger.info("Returning empSaveSuccess.jsp page");
model.addAttribute("emp", employee);
emps.put(employee.getId(), employee);
return "empSaveSuccess";
}
}
For using custom validator, first we need to inject it in the controller class. We are using spring bean auto wiring to achieve this using @Autowired
and @Qualifier
annotations. Next we need to have a method that will take WebDataBinder as argument and we set our custom validator to be used. This method should be annotated with @InitBinder
annotation. Using @ModelAttribute
is another way to add our bean object to the Model. Rest of the code is similar to customer controller implementation.
It’s time to look at our resource bundle where we have different types of messages to be used for validation errors. message_en.properties file:
#application defined error messsages
id.required=Employee ID is required
name.required=Employee Name is required
role.required=Employee Role is required
negativeValue={0} can't be negative or zero
#Spring framework error messages to be used when conversion from form data to bean fails
typeMismatch.int={0} Value must be an integer
typeMismatch.java.lang.Integer={0} must be an integer
typeMismatch={0} is of invalid format
#application messages for annotations, {ValidationClass}.{modelObjectName}.{field}
#the {0} is field name, other fields are in alphabatical order, max and then min
Size.customer.name=Customer {0} should be between {2} and {1} characters long
NotEmpty.customer.email=Email is a required field
NotNull.customer.age=Customer {0} should be in years
#Generic annotation class messages
Email=Email address is not valid
NotNull=This is a required field
NotEmpty=This is a required field
Past=Date should be Past
#Custom validation annotation
Phone=Invalid format, valid formats are 1234567890, 123-456-7890 x1234
I have provided message key details in the comment itself, so I will skip them here. The only important point to note here is the way messages will be looked up, first key name {ValidationClass}.{modelObjectName}.{field} is looked up and if that is not found then {ValidationClass}.{modelObjectName} is looked up. If that is missing, then finally {ValidationClass} key is looked up. If nothing is found then the default message provided will be returned. Read more about resource messages at Spring Localization Example.
Since we are using Spring framework validation implementation, we will have to use Spring Form tags to get the errors and set the form bean and variable names. Our custSave.jsp file code is given below.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="https://www.springframework.org/tags/form"
prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer Save Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body>
<springForm:form method="POST" commandName="customer"
action="save.do">
<table>
<tr>
<td>Name:</td>
<td><springForm:input path="name" /></td>
<td><springForm:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Email:</td>
<td><springForm:input path="email" /></td>
<td><springForm:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Age:</td>
<td><springForm:input path="age" /></td>
<td><springForm:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><springForm:select path="gender">
<springForm:option value="" label="Select Gender" />
<springForm:option value="MALE" label="Male" />
<springForm:option value="FEMALE" label="Female" />
</springForm:select></td>
<td><springForm:errors path="gender" cssClass="error" /></td>
</tr>
<tr>
<td>Birthday:</td>
<td><springForm:input path="birthday" placeholder="MM/dd/yyyy"/></td>
<td><springForm:errors path="birthday" cssClass="error" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><springForm:input path="phone" /></td>
<td><springForm:errors path="phone" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Save Customer"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
commandName="customer"
is used to set the name of the model attribute under which form object is exposed. Its default value is “command” by default, hence we should set it to the model attribute name we are using in our controller classes. springForm:errors
is used to render the errors, if any, found when the page is rendered. path
attribute is used to define the object property to be used for data binding. Rest of the code is standard HTML with some CSS for error messages styling. Our custSaveSuccess.jsp file is given below.
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<%@ page session="false" %>
<html>
<head>
<title>Customer Saved Successfully</title>
</head>
<body>
<h3>
Customer Saved Successfully.
</h3>
<strong>Customer Name:${customer.name}</strong><br>
<strong>Customer Email:${customer.email}</strong><br>
<strong>Customer Age:${customer.age}</strong><br>
<strong>Customer Gender:${customer.gender}</strong><br>
<strong>Customer Birthday:<fmt:formatDate value="${customer.birthday}" type="date" /></strong><br>
</body>
</html>
Simple JSP page showing the customer values if there are no validation errors and this page is returned as response. Its name is empSave.jsp.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="https://www.springframework.org/tags/form"
prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Save Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body>
<springForm:form method="POST" commandName="employee"
action="save.do">
<table>
<tr>
<td>Employee ID:</td>
<td><springForm:input path="id" /></td>
<td><springForm:errors path="id" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><springForm:input path="name" /></td>
<td><springForm:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Role:</td>
<td><springForm:select path="role">
<springForm:option value="" label="Select Role" />
<springForm:option value="ceo" label="CEO" />
<springForm:option value="developer" label="Developer" />
<springForm:option value="manager" label="Manager" />
</springForm:select></td>
<td><springForm:errors path="role" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Save"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
empSaveSuccess.jsp file:
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Employee Saved Successfully</title>
</head>
<body>
<h3>
Employee Saved Successfully.
</h3>
<strong>Employee ID:${emp.id}</strong><br>
<strong>Employee Name:${emp.name}</strong><br>
<strong>Employee Role:${emp.role}</strong><br>
</body>
</html>
Our application is ready to deploy and run some tests, deploy it in your favorite servlet container. I am using Apache Tomcat 7 and below images show some of the pages with validation error messages. Based on your input data, you might get different error messages too.
That’s all for Spring MVC Form validation with different ways and using resource bundles for localized error messages. You can download the sample project from below link and play around with it to learn more.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
hi, coud you upload again the zip file. thanks
- eduardo
it was an issue with the plugin I use for managing downloads, solved it. Please try now.
- Pankaj
Hi Pankaj, the article has been very useful for me to pickup the basics. Thank you very much
- Rajesh Antony
{Phone} validation is not showing the value from resource bundle Adjacent to the phone it is showing key instead of value {Phone}
- Anil
Your site is really good with the examples provided for java and spring framework. Could you post an article on Spring AOP concepts using annotations
- santhosh
Its already posted, check the Spring category articles.
- Pankaj
Really great concepts of vaidation thanks a lot…
- Tanuja
such nice deep concept…
- dev
hi pankaj very nice explanation … could you post webservice example.wre webservices r useful in real time?
- kumar
Thank you for this useful tutorial! Please add message.properties file to src/main/resources folder. Spring cannot resolve bound if there is no default properties file and client uses another locale. For example, for my locale “_ru” I’ve got default text message or exception stack trace instead of text from message_en.properties.
- Dmytro
Thanks for the suggestion.
- Pankaj
I have default message from stack trace as well. What’s wrong? I’ve added message.properties file to resources folder
- Vlad
I see that you have defined a messageSource bean in your Spring bean configuration file. Where does this bean get used? I don’t see a place where it gets auto wired. Can you please explain how Spring internally works to get messages from this bean. Is the bean name “messageSource” special to Spring MVC? Does this bean need to be named with that name?
- Rahul
It’s to load messages property files, it’s used for localization, read more at https://www.journaldev.com/2610/spring-mvc-internationalization-i18n-and-localization-l10n-example You can keep any other name, but in that case you will have to bind it manually, with this name it’s autowired.
- Pankaj
Pankaj, thanks for the quick feedback. You are right. I just tried this. Yes I need to name the Message Source bean as “messageSource” for it to be picked up.
- Rahul
Not able to download the zip even after following on Twitter.
- Ashirwad Kumar
Thanks for the post, it is really helpful. I was wondering how validation can be done in case we have @OneToMany mapping (say Employee class has Set of Address and none of the address field is inputted by the user from frontend, thus returning NULL to Spring MVC)? Thanks in advance,
- Sandeep
Hi Sandeep, @OneToMany mapping is totally depends on @Request Mapping of URL and NULL value is coming only on that case Regards Adarsh
- Adarsh
Could you include a snippet to give errors in a json result and include Ajax Request?
- Kanika
Hi Kanika The JSON request bind with JSONRequest of controller context public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (!IsJSONRequest(controllerContext)) { return base.BindModel(controllerContext, bindingContext); } pls see above code for manipulate the JSON Request
- Adarsh
Hello, Pankaj! Please, change the Hibernate version in dependency from 5 to 4: org.hibernate hibernate-validator 4.1.0.Final
- Max
Thanks, corrected the typo error.
- Pankaj
Thanks alot very helpful.
- abdul
hi pankaj,well explained. I am facing problem while running this project.My tomcat is going blank after running this project on eclipse usin tomcat:run in configuration. Kindly let me know the reason this. Outside of eclipse tomcat is running perfectly
- bindu
Hi Bindu, If application is running fine when tomcat is not launched from Eclipse, it means everything is fine. I would suggest you to add a fresh server to Eclipse and try again, some issues with the current configured server might be causing this. Also check the URL in browser when app is launched in Eclipse.
- Pankaj
Tomcat Server showing blank page when started from eclipse : ‘Your Project is not working’ WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/custSave] in DispatcherServlet with name ‘appServlet’
- NHP
Very nice explanation, Pankaj!! I have a situation to validate the date for Future and today!! We have @Future annotation. Can you please help me to validate today’s date? Appreciate your help. Thanks in advance!!
- Rajasekhar Balusupati
Hi, Please give me one solution in spring frame work for the below scenario, 1. If I click or submit any action in jsp, that action name should be configured aginst the controller in the spring config xml. 2. Once the flow has gone to Controller, ModelView will return success, failure or any constant string. 3. Based on that string, view will be redirected based on the configuration in the same config. 4. Different method name will be used in the same controller. Problem should be addressed:: 1. We have to identify the method name in the controller by action name and go to that method and come back to the spring config xml and redirect the view based on the string returned from the controller. I am waiting for your response… Thank You… Vijay G .
- Vijay G
I add new plugins in pom.xml org.apache.tomcat.maven tomcat7-maven-plugin 2.2 and org.eclipse.jetty jetty-maven-plugin 9.0.6.v20130930 /${project.artifactId} When I start tomcat by command : mvn tomcat7:run or mvn jetty-run. I have an error: Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider; at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:196) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:181) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) … 66 more Can you explain my error and how to fix it. Thanks
- Hieu
I add new plugins in pom.xml For tomcat plugin
org.apache.tomcat.maven tomcat7-maven-plugin 2.2 ````` and for jetty plugin ```` org.eclipse.jetty jetty-maven-plugin 9.0.6.v20130930 /${project.artifactId} ``` When I start tomcat by command : mvn tomcat7:run or mvn jetty-run. I have an error: `` Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider; at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:196) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:181) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) … 66 more `Can you explain my error and how to fix it. Thanks` `` ``` ```` `````
- Hieu
Hi Pankaj Sir, I do appreciate you each ans every topics explanation as which helped a lot to develop my website. I have deployed the above project and without using pom.xml (means not maven) and facing below error. Am i missing any jar file ? Please provide your guide line . org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerController’ defined in file [D:\WORK\Spring3MVC4Site\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Spring3MVCFormValidation\WEB-INF\classes\com\journaldev\spring\form\controllers\CustomerController.class]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.journaldev.spring.form.controllers.CustomerController org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) java.lang.Thread.run(Unknown Source) Thanks, Vinod Paliwal
- Vinod Paliwal
update your hibernate-validator version and try again, this is work for me. org.hibernate hibernate-validator 5.1.0.Final
- Andy
Thanks for the post, it is really helpful. I was wondering how validation can be done in case we have @OneToMany mapping (say Employee class has Set of Address and none of the address field is inputted by the user from frontend, thus returning NULL to Spring MVC)? Thanks in advance,
- Sandeep
Hi Sandeep, @OneToMany mapping is totally depends on @Request Mapping of URL and NULL value is coming only on that case Regards Adarsh
- Adarsh
Could you include a snippet to give errors in a json result and include Ajax Request?
- Kanika
Hi Kanika The JSON request bind with JSONRequest of controller context public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (!IsJSONRequest(controllerContext)) { return base.BindModel(controllerContext, bindingContext); } pls see above code for manipulate the JSON Request
- Adarsh
Hello, Pankaj! Please, change the Hibernate version in dependency from 5 to 4: org.hibernate hibernate-validator 4.1.0.Final
- Max
Thanks, corrected the typo error.
- Pankaj
Thanks alot very helpful.
- abdul
hi pankaj,well explained. I am facing problem while running this project.My tomcat is going blank after running this project on eclipse usin tomcat:run in configuration. Kindly let me know the reason this. Outside of eclipse tomcat is running perfectly
- bindu
Hi Bindu, If application is running fine when tomcat is not launched from Eclipse, it means everything is fine. I would suggest you to add a fresh server to Eclipse and try again, some issues with the current configured server might be causing this. Also check the URL in browser when app is launched in Eclipse.
- Pankaj
Tomcat Server showing blank page when started from eclipse : ‘Your Project is not working’ WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/custSave] in DispatcherServlet with name ‘appServlet’
- NHP
Very nice explanation, Pankaj!! I have a situation to validate the date for Future and today!! We have @Future annotation. Can you please help me to validate today’s date? Appreciate your help. Thanks in advance!!
- Rajasekhar Balusupati
Hi, Please give me one solution in spring frame work for the below scenario, 1. If I click or submit any action in jsp, that action name should be configured aginst the controller in the spring config xml. 2. Once the flow has gone to Controller, ModelView will return success, failure or any constant string. 3. Based on that string, view will be redirected based on the configuration in the same config. 4. Different method name will be used in the same controller. Problem should be addressed:: 1. We have to identify the method name in the controller by action name and go to that method and come back to the spring config xml and redirect the view based on the string returned from the controller. I am waiting for your response… Thank You… Vijay G .
- Vijay G
I add new plugins in pom.xml org.apache.tomcat.maven tomcat7-maven-plugin 2.2 and org.eclipse.jetty jetty-maven-plugin 9.0.6.v20130930 /${project.artifactId} When I start tomcat by command : mvn tomcat7:run or mvn jetty-run. I have an error: Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider; at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:196) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:181) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) … 66 more Can you explain my error and how to fix it. Thanks
- Hieu
I add new plugins in pom.xml For tomcat plugin
org.apache.tomcat.maven tomcat7-maven-plugin 2.2 ````` and for jetty plugin ```` org.eclipse.jetty jetty-maven-plugin 9.0.6.v20130930 /${project.artifactId} ``` When I start tomcat by command : mvn tomcat7:run or mvn jetty-run. I have an error: `` Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider; at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:196) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:181) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) … 66 more `Can you explain my error and how to fix it. Thanks` `` ``` ```` `````
- Hieu
Hi Pankaj Sir, I do appreciate you each ans every topics explanation as which helped a lot to develop my website. I have deployed the above project and without using pom.xml (means not maven) and facing below error. Am i missing any jar file ? Please provide your guide line . org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerController’ defined in file [D:\WORK\Spring3MVC4Site\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Spring3MVCFormValidation\WEB-INF\classes\com\journaldev\spring\form\controllers\CustomerController.class]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.journaldev.spring.form.controllers.CustomerController org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) java.lang.Thread.run(Unknown Source) Thanks, Vinod Paliwal
- Vinod Paliwal
update your hibernate-validator version and try again, this is work for me. org.hibernate hibernate-validator 5.1.0.Final
- Andy
Thanks for the post, it is really helpful. I was wondering how validation can be done in case we have @OneToMany mapping (say Employee class has Set of Address and none of the address field is inputted by the user from frontend, thus returning NULL to Spring MVC)? Thanks in advance,
- Sandeep
Could you include a snippet to give errors in a json result and include Ajax Request?
- Kanika
Hello, Pankaj! Please, change the Hibernate version in dependency from 5 to 4: org.hibernate hibernate-validator 4.1.0.Final
- Max
Thanks alot very helpful.
- abdul
hi pankaj,well explained. I am facing problem while running this project.My tomcat is going blank after running this project on eclipse usin tomcat:run in configuration. Kindly let me know the reason this. Outside of eclipse tomcat is running perfectly
- bindu
Tomcat Server showing blank page when started from eclipse : ‘Your Project is not working’ WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/custSave] in DispatcherServlet with name ‘appServlet’
- NHP
Very nice explanation, Pankaj!! I have a situation to validate the date for Future and today!! We have @Future annotation. Can you please help me to validate today’s date? Appreciate your help. Thanks in advance!!
- Rajasekhar Balusupati
Hi, Please give me one solution in spring frame work for the below scenario, 1. If I click or submit any action in jsp, that action name should be configured aginst the controller in the spring config xml. 2. Once the flow has gone to Controller, ModelView will return success, failure or any constant string. 3. Based on that string, view will be redirected based on the configuration in the same config. 4. Different method name will be used in the same controller. Problem should be addressed:: 1. We have to identify the method name in the controller by action name and go to that method and come back to the spring config xml and redirect the view based on the string returned from the controller. I am waiting for your response… Thank You… Vijay G .
- Vijay G
I add new plugins in pom.xml org.apache.tomcat.maven tomcat7-maven-plugin 2.2 and org.eclipse.jetty jetty-maven-plugin 9.0.6.v20130930 /${project.artifactId} When I start tomcat by command : mvn tomcat7:run or mvn jetty-run. I have an error: Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider; at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:196) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:181) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) … 66 more Can you explain my error and how to fix it. Thanks
- Hieu
Hi Pankaj Sir, I do appreciate you each ans every topics explanation as which helped a lot to develop my website. I have deployed the above project and without using pom.xml (means not maven) and facing below error. Am i missing any jar file ? Please provide your guide line . org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerController’ defined in file [D:\WORK\Spring3MVC4Site\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Spring3MVCFormValidation\WEB-INF\classes\com\journaldev\spring\form\controllers\CustomerController.class]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.journaldev.spring.form.controllers.CustomerController org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) java.lang.Thread.run(Unknown Source) Thanks, Vinod Paliwal
- Vinod Paliwal
“When you create Spring MVC project from STS, it creates two context configuration files. I have cleaned it up a bit and have only one spring bean configuration file. My final web.xml file looks like below.” Where are the original two? I only see the one web.xml.
- Zac C
For the save page, when you run save.do, the number 0 is defaulted into the “Employee ID” field. How’d you get that to default to zero? What if I wanted employer name and employee role to default to null.
- Zac C
Hi Pankaj, Can we have custom validation and annotation validation together. Say for example in Customer I want to have annotation validation for all field except for age, for age I want to use validator class. Is that possible. Regards, Dinesh Pise
- Dinesh Pise
Thanks a lot , its very useful.
- koushal
Your tutorials are some of the best I have seen, Thank You
- David Adkins
Hi, Your articles are very useful. I have tried to built the application and deploy it on JBOSS. But I got an error " ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[defaulthost].[/spring-1.0.0-BUILD-SNAPSHOT]] (ServerService Thread Pool – 57) JBWEB000289: Servlet spring threw load() exception: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/spring.xml]" . Could you please help me to resolve the same. Thank you
- kunal
How to validation int array in server side in java spring
- IMRAN AHMAD
Hi Pankaj, Thanks, example is good. I have two question regarding Spring MVC validation. I want to know how to register more than one validators for single command object by using @IntBinder annotated method so that I need not to call them explicitly in my controller method for validation. My second question is I want to use JSR 303 validation annotation such as @NotBlank as well as my own custom designed validation annotation for example @Phone ( which you have shown in this example) but these two validation are annotations are different then how can I use them without loosing other one? Can I use @Valid @Validated to command argument of request handling method of controller or there is some other way. Wanting for your reply
- Farhan
localhost:8080/SpringFormValidation/emp/save.do showing HTTP 404 error. Not getting the form page. !!A
- Aatif
please help me out in one problem related to validation how to validate the Path Variable in spring application? if possible then please provide me example also.
- Ankit kumar gupta
Cannot find class [com.journaldev.spring.form.validator.EmployeeFormValidator] for bean with name ‘employeeValidator’ defined in ServletContext resource [/WEB-INF/spring/spring.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.form.validator.EmployeeFormValidator I am getting this error while running.I have checked all possibilities but unable to resolve Could you please help me.??
- Manas Kumar
explained in detail thanks
- Arun SIngh
Hi, The article is so good , but in real time no body will go for spring validation approach to validate form . client side validation is simple and good, any body really use spring validator for validation ?
- shan
wonderful article, clear, full functional.
- kevin
Nice, good explanation with spring mvc integration with rest webservices, can we integrate soap with spring mvc?
- guru
Jul 31, 2019 5:23:22 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [jsp] in context with path [/Spring_Howtodo] threw exception [java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘employee’ available as request attribute] with root cause java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘employee’ available as request attribute at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:147) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:138) at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:122) at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:409) at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140) at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102) at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79) at org.apache.jsp.empSave_jsp._jspx_meth_springForm_005finput_005f0(empSave_jsp.java:434) at org.apache.jsp.empSave_jsp._jspService(empSave_jsp.java:137) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:724)
- kolanjinathan
I have implemented validator using org.springframework.validation.Validator (that you have done for employee class). Eveythine works fine but when I add @Size(min = 1, max = 6,message = “Size.course.title”) in my Entity class 's field(title) it doesn’t work. ERROR: SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/CourseWebApp] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause javax.validation.ConstraintViolationException: Validation failed for classes [net.therap.model.Course] during update time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage=‘Size.course.title’, propertyPath=title, rootBeanClass=class net.therap.model.Course, messageTemplate=‘Size.course.title’} ] at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140) at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:88) … Note: I have a dao layer calling to validate duplicate tilte inside my validate method of Validator interface implementation.
- Wafi