Spring MVC Validation Example

Spring MVC Validation Example explains about handling the form validation in Spring MVC web application, Here we are using eclipse ide as dev environment

Spring version 4.0 provides full support for the latest Java 8 features.

Spring MVC is a popular Java Model-View-Contraller (MVC) framework. Basically spring is request based framework, which revolve around DispatcherServlet that dispatches the requests with the help of different lifecycle interfaces

Using Spring MVC, we can easily handle form validations and other error handling techniques with maximum flexibility and minimum changes.

Note

You can also read about implementing a REST service using Spring MVC below

Spring MVC 4 REST Example

Required Libraries
  1. JDK 6
  2. Eclipse 3.7
  3. Spring 4.0.5

Following jar must be in classpath

  1. commons-logging-1.1.1.jar
  2. hibernate-validator-4.3.1.Final.jar
  3. jboss-logging-3.2.0.Final.jar
  4. spring-aop-4.0.5.RELEASE.jar
  5. spring-beans-4.0.5.RELEASE.jar
  6. spring-context-4.0.5.RELEASE.jar
  7. spring-core-4.0.5.RELEASE.jar
  8. spring-expression-4.0.5.RELEASE.jar
  9. spring-web-4.0.5.RELEASE.jar
  10. spring-webmvc-4.0.5.RELEASE.jar
  11. validation-api-1.0.0.GA.jar

You can see the project structure below

Spring MVC Validation Example

studentForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>

<title>Spring MVC Form Handling</title>
</head>
<h2>Student Data Form</h2>
<form:form action="addStudent" commandName='student' method="POST">
	<table>
		<tbody>
			<tr>
				<td><form:label path="studId">Student ID:</form:label></td>
				<td><form:input path="studId"></form:input>
				<font color="red"><form:errors path="studId"></form:errors></font>
				</td>
			</tr>
			<tr>
				<td><form:label path="name">StudentName :</form:label></td>
				<td><form:input path="name"></form:input>
					<font color="red"><form:errors path="name"></form:errors></font>
				</td>
			</tr>
			<tr>
				<td><form:label path="age">Student Age:</form:label></td>
				<td><form:input path="age"></form:input>
				<font color="red"><form:errors path="age"></form:errors></font>
				</td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Submit" />
				</td>
			</tr>
		</tbody>
	</table>
</form:form>
</body>
</html>

studentDetail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
	<h2>Submitted Student Information</h2>
	<table border="1">
		<tbody>
			<tr>
				<td>Student ID</td>
				<td>${studId}</td>
			</tr>
			<tr>
				<td>Student Name</td>
				<td>${name}</td>
			</tr>
			<tr>
				<td>Student Age</td>
				<td>${age}</td>
			</tr>
		</tbody>
	</table>
</body>
</html>

Student.java

Below class, we can see that we are using annotations such as @NotNull,@Size(min=5, max=20) etc for validating the fields.

package com.student.bean;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Student {
   
@NotNull
   
private Integer        studId;
   
@NotNull
    @Size
(min=5, max=20)
   
private String    name;
   
@NotNull
    @Min
(5)
   
private Integer        age;

   
public Integer getStudId() {
       
return studId;
   
}

   
public void setStudId(Integer studId) {
       
this.studId = studId;
   
}

   
public String getName() {
       
return name;
   
}

   
public void setName(String name) {
       
this.name = name;
   
}

   
public Integer getAge() {
       
return age;
   
}

   
public void setAge(Integer age) {
       
this.age = age;
   
}

}

StudentController.java

In StudentController class, we have added @Controller annotation which indicates that an annotated class is a "Controller" (e.g. a web controller)

@RequestMapping annotation is used for mapping web requests to corresponding handler classes and handler methods

@ModelAttribute annotation is used for backing up the model object and persisted across requests

package com.student.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.student.bean.Student;

@Controller
public class StudentController {

   
@RequestMapping(value = "/student", method = RequestMethod.GET)
   
public ModelAndView student() {
       
return new ModelAndView("studentForm", "student", new Student());
   
}

   
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   
public String addStudent(@ModelAttribute("student") @Valid Student student, BindingResult result, ModelMap model) {
       
if(result.hasErrors()) {
           
return "studentForm";
       
}
       
model.addAttribute("name", student.getName());
        model.addAttribute
("age", student.getAge());
        model.addAttribute
("studId", student.getStudId());
       
return "studentDetail";
   
}
}

spring-servlet.xml

The name for spring-servlet.xml is must match the servlet-name we have provided on web.xml. In our case we have provided servlet-name as spring, so we need to append "-servlet.xml"

Below code is used for Spring auto detection feature to find the packages where the controller is defined

<context:component-scan base-package="com.student" />
<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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<mvc:annotation-driven />
	<context:component-scan base-package="com.student.controller" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		id="viewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="/WEB-INF/messages" />
   </bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">

	<display-name>SpringMVCExample</display-name>
	<welcome-file-list>
		<welcome-file>/</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

messages.properties

NotNull.student.studId=Student ID must not be blank.
Size.student.name=Student Name must be between 5 to 20 characters.
NotNull.student.age=Student Age must be Atleast 5 year old.
Run

Spring MVC Validation Example

Spring MVC Validation Example

Spring MVC Validation Example

Spring MVC Validation Example









Your email address will not be published. Required fields are marked *