Last updated on February 28th, 2024
In this example, we can use the required field form validation through Bean and Hibernate validations in Spring MVC. In this example, we are taking two text fields, one is mandatory when entering some input and another is optional then click to submit after we will show another page otherwise we will show the same page with some message “is required” for validation.
Development Process:
1. Keep eclipse IDE ready
2. Project Structure
3. Add the jar file
4. Configure Spring DispacherServlet
5. Add configuration to file
6. Create Bean Class
7. Create View Page
8. Create Controller Class
9. Run the App
1. Keep eclipse IDE ready
2. Project Structure
3. Add the jar file
4. Configure Spring DispacherServlet
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4.xsd" id="WebApp_ID" version="4.0">
<display-name>spring-mvc-required-field-validation-demo</display-name>
<absolute-ordering />
<!-- Spring MVC Configs -->
<!-- Configure Spring MVC Dispatcher Servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
→ The file is created at the WEB-INF directory of the application i.e., spring_mvc_required_field_validation_demo
5. Add configuration to file
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.poc" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
6. Create Bean Class
User.java:
package com.poc.controller.bean;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotNull(message = "is required")
@Size(min=1,message = "is required")
private String firstName;
private String lastName;
public User() {
}
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;
}
}
→ Add validation rule in this bean class we are using @NotNull(message = “is required”) is validating field is not null if the empty then the message is shown.
→ @Size(min=1, message = “is required”) is validating the size of at least 1 character if it failed to validate then the message is shown.
7. Create View Page
home.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<body>
<a href="http://localhost:8080/spring_mvc_required_field_validation_demo/user/showForm">Click For User Form</a>
</body>
</html>
user-form.jsp:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
<style>
.error {color:red}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="user">
First name (*): <form:input path="firstName" />
<form:errors path="firstName" cssClass="error" />
<br>
<br>
Last name: <form:input path="lastName" />
<br>
<br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
→ <form:errors path=”firstName” cssClass=”error” /> is displaying a message when the first name field failed to validate the rule.
user-detail.jsp:
<!DOCTYPE html>
<html>
<head>
<title>User Detail</title>
</head>
<body>User Detail: ${user.firstName} ${user.lastName}
</body>
</html>
8. Create Controller Class
HomeController.java:
package com.poc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String showPage() {
return "home";
}
}
UserController.java:
package com.poc.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.poc.controller.bean.User;
@Controller
@RequestMapping("/user")
public class UserController{
@RequestMapping("/showForm")
public String showForm(Model theModel) {
// create a User object
User user=new User();
theModel.addAttribute("user",user);
return "user-form";
}
@RequestMapping("/processForm")
public String processValidation(@ModelAttribute("user") @Valid User user,BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return "user-form";
}
else {
return "user-detail";
}
}
}
→ @Valid is used for validation rules on the User object.
→ The result of validation is put on the BindingResult Interface.
9. Run the App
Conclusion
This example is explained How to use required field validation? How to apply validation rules to the Bean class? How to use <form:errors/> tag?