📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Before you get started, check out Spring Data JPA Tutorial and Spring MVC Tutorial
Spring MVC Tutorials and Articles
- Spring MVC 5 - Hello World Example
- Spring MVC 5 - Sign Up Form Handling Example
- Spring MVC JSP Form Tags Tutorial
- Spring MVC 5 Form Validation with Annotations Tutorial
- Spring MVC 5 + Hibernate 5 + JSP + MySQL CRUD Tutorial
- Spring MVC 5 + Spring Data JPA + Hibernate 5 + JSP + MySQL Tutorial
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring Boot 2 - Spring MVC + Thymeleaf Input Form Validation
- Spring Boot 2 + Spring MVC + Spring Security + JPA + Thymeleaf + MySQL Tutorial
- Authenticating a User with LDAP using Spring Boot and Spring Security
- The Spring @Controller and @RestController Annotations with Examples
- Spring @RequestBody and @ResponseBody Annotations
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping
- Spring Web MVC Annotations
- Mini Todo Management Project using Spring Boot + Spring MVC + Spring Security
- User Registration Module using Spring Boot + Spring MVC + Spring Security + Hibernate 5
- 20+ Free Open Source Projects Using Spring Framework
Important Java bean validations
- @NotNull validates that the annotated property value is not null.
- @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.
- @Min validates that the annotated property has a value not smaller than the value attribute.
- @Max validates that the annotated property has a value no larger than the value attribute.
- @Email validates that the annotated property is a valid email address.
- @NotEmpty validates that the property is not null or empty; can be applied to String, Collection, Map, or Array values.
- @NotBlank can be applied only to text values and validates that the property is not null or whitespace.
Tools and technologies used
- Spring MVC - 5.1.0 RELEASE
- JDK - 1.8 or later
- Maven - 3.5.1
- Apache Tomcat - 8.5
- IDE - STS/Eclipse Neon.3
- JSTL - 1.2.1
- JSP - 2.3.1
Development Steps
- Create Maven Web Application
- Add Dependencies - pom.xml File
- Project Structure
- Spring Configuration - MVCConfig.java
- Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java
- Model Class - Customer.java
- Controller Class - CustomerController.java
- Views - customer-form.jsp and customer-confirmation.jsp
- Build and Run an application
- Demo
1. Create Maven Web Application
2. Add Dependencies - pom.xml File
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javaguides.springmvc</groupId>
<artifactId>springmvc5-form-validation</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springmvc5-form-validation Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Project Structure
4. Spring Configuration - MVCConfig.java
package net.javaguides.springmvc.form.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* @author Ramesh Fadatare
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
"net.javaguides.springmvc.form"
})
public class MVCConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
- The @Configuration is a class-level annotation indicating that an object is a source of bean definitions.
- The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to mvc:annotation-driven/ element in XML based configuration.
- The @ComponentScan scans the stereotype annotations (@Controller, @Service etc...) in a package specified by basePackages attribute.
5. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java
package net.javaguides.springmvc.form.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @author Ramesh Fadatare
*/
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class << ? > [] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class << ? > [] getServletConfigClasses() {
return new Class[] {
MVCConfig.class
};
}
@Override
protected String[] getServletMappings() {
return new String[] {
"/"
};
}
}
6. Model Class - Customer.java
package net.javaguides.springmvc.form.model;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class Customer {
private String firstName;
@NotNull(message = "is required")
@Size(min = 1, message = "is required")
private String lastName;
@NotNull(message = "is required")
@Min(value = 0, message = "must be greater than or equal to zero")
@Max(value = 10, message = "must be less than or equal to 10")
private Integer freePasses;
@Pattern(regexp = "^[a-zA-Z0-9]{5}", message = "only 5 chars/digits")
private String postalCode;
@NotNull(message = "is required")
@Email(message = "Invalid email! Please enter valid email")
private String email;
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public Integer getFreePasses() {
return freePasses;
}
public void setFreePasses(Integer freePasses) {
this.freePasses = freePasses;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
7. Controller Class - CustomerController.java
package net.javaguides.springmvc.form.controller;
import javax.validation.Valid;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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 net.javaguides.springmvc.form.model.Customer;
@Controller
@RequestMapping("/customer")
public class CustomerController {
// add an initbinder ... to convert trim input strings
// remove leading and trailing whitespace
// resolve issue for our validation
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}
@RequestMapping("/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
@RequestMapping("/processForm")
public String processForm(
@Valid @ModelAttribute("customer") Customer theCustomer,
BindingResult theBindingResult) {
if (theBindingResult.hasErrors()) {
return "customer-form";
} else {
return "customer-confirmation";
}
}
}
8. Views - customer-form.jsp and customer-confirmation.jsp
customer-form.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Customer Registration Form</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
<h1> Spring MVC 5 - Form Validation Example</h1>
<i>Fill out the form. Asterisk (*) means required.</i>
<br><br>
<form:form action="processForm" modelAttribute="customer">
First name:
<form:input path="firstName" />
<br><br> Last name (*):
<form:input path="lastName" />
<form:errors path="lastName" cssClass="error" />
<br><br> Free passes (*):
<form:input path="freePasses" />
<form:errors path="freePasses" cssClass="error" />
<br><br> Email (*):
<form:input path="email" />
<form:errors path="email" cssClass="error" />
<br><br> Postal Code:
<form:input path="postalCode" />
<form:errors path="postalCode" cssClass="error" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
customer-confirmation.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Customer Confirmation</title>
</head>
<body>
The customer is confirmed: ${customer.firstName} ${customer.lastName}
<br><br> Free passes: ${customer.freePasses}
<br><br> Email: ${customer.email}
<br><br> Postal Code: ${customer.postalCode}
</body>
</html>
9. Build and Run an application
clean install
Comments
Post a Comment
Leave Comment