Spring MVC verifier application example (super detailed)

Posted by InO on Fri, 18 Feb 2022 14:34:15 +0100

This section uses an application springMVCDemo08 to explain the preparation and use of Spring validator. The application has a data entry page addgoods JSP, the effect is shown in Figure 1.

There is a data display page goodslist JSP, the effect is shown in Figure 2.

Write an implementation org springframework. validation. The validator class of goodvalidator requires the following validators:

  • The commodity name and commodity details cannot be blank.
  • Commodity prices range from 0 to 100.
  • The creation date cannot be later than the system date.

According to the above requirements, complete the application of springMVCDemo08 according to the following steps.

1) Create application

Create a springMVCDemo08 application and import the relevant JAR package of Spring MVC. In addition, you need to use JSTL tags to display data, so you need to import the JAR package of JSTL.

The JAR package required by springMVCDemo08 is the same as the application of springMVCDemo04 in the tutorial of Spring MVC data binding and form tags, which will not be repeated here.

2) Create data entry page

Create a folder JSP under the WEB-INF directory, and create a data input page addgoods jsp. The code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add item</title>
    <form:form modelAttribute="goods"
        action="${pageContext.request. contextPath }/goods/save" method="post">
            <legend> Add an item </legend>
                <label>Trade name:</label>
                <form:input path="gname" />
                <label>Product details:</label>
                <form:input path="gdescription" />
                <label>commodity price:</label>
                <form:input path="gprice" />
                <label>Creation date:</label>
                <form:input path="gdate" />
            <p id="buttons">
                <input id="reset" type="reset">
                <input id="submit" type="submit" value="add to">
        <!-- Remove all validation errors -->
        <form:errors path="*" />

3) Write model classes

Create a pojo package in the src directory, define the domain model class Goods in the package, and encapsulate the input parameters. Use @ DateTimeFormat (pattern = "yyyy MM DD") to format the creation date in this class.

The specific code of the model class Goods is as follows:

package pojo;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class Goods {
    private String gname;
    private String gdescription;
    private double gprice;
    // Date formatting (formattingconversionservicefactorybean needs to be configured in the configuration file)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date gdate;
    public String getGname() {
        return gname;
    public void setGname(String gname) {
        this.gname = gname;
    public String getGdescription() {
        return gdescription;
    public void setGdescription(String gdescription) {
        this.gdescription = gdescription;
    public double getGprice() {
        return gprice;
    public void setGprice(double gprice) {
        this.gprice = gprice;
    public Date getGdate() {
        return gdate;
    public void setGdate(Date gdate) {
        this.gdate = gdate;

4) Write verifier class

Create the validator package under the src directory, and write the implementation org. Org in the package springframework. validation. Validator class GoodsValidator of validator interface, declare GoodsValidator class as validation component with @ Component annotation. The specific codes are as follows:

package validator;
import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import pojo.Goods;
public class GoodsValidator implements Validator {
    public boolean supports(Class<?> klass) {
        // If the return value of the model to be verified is false, it will not be verified
        return Goods.class.isAssignableFrom(klass);
    public void validate(Object object, Errors errors) {
        Goods goods = (Goods) object; // Object object to validate
        // goods.gname.required is the code in the error message attribute file (after internationalization, the corresponding information is internationalized)
        ValidationUtils.rejectIfEmpty(errors, "gname", "goods. gname.required");
        ValidationUtils.rejectIfEmpty(errors, "gdescription",
        if (goods.getGprice() > 100 || goods.getGprice() < 0) {
            errors.rejectValue("gprice", "gprice.invalid");
        Date goodsDate = goods.getGdate();
        // After system time
        if (goodsDate != null && goodsDate.after(new Date())) {
            errors.rejectValue("gdate", "gdate.invalid");

5) Write error message properties file

Create a folder resource under the WEB-INF directory, and write the property file errormessages properties. The contents of the document are as follows:

goods.gname.required=Please enter the product name
goods.gdescription.required=Please enter product details
gprice.invalid=The price is 0~100
gdate.invalid=The creation date cannot be later than the system date

The content of the attribute file of Unicode encoding (MyEclipse has the function of converting Chinese characters into Unicode encoding) is as follows:


After the property file is created, you need to tell Spring MVC to get the error message from the file. You need to declare a messageSource bean in the configuration file. The specific code is as follows:

<!-- Configure message properties file -->
<bean id="messageSource"
    <property name="basename" value="/WEB-INF/resource/errorMessages" />

6) Write Service layer

Create a service package in the src directory and write a GoodsService interface in the package. The specific codes are as follows:

package service;
import java.util.ArrayList;
import pojo.Goods;
public interface GoodsService {
    public boolean save(Goods g);
    public ArrayList<Goods> getGoods();

The specific code of GoodsServiceImpl implementation class is as follows:

package service;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import pojo.Goods;
public class GoodsServiceImpl implements GoodsService {
    // Simulate the database with the static set variable goods
    private static ArrayList<Goods> goods = new ArrayList<Goods>();
    public boolean save(Goods g) {
        return true;
    public ArrayList<Goods> getGoods() {
        return goods;

7) Write controller class

Create the @ src class in the custom controller package and inject it into the controller package using the @ src class annotation. In addition, the controller class contains two methods for processing requests. The specific codes are as follows:

package controller;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Goods;
import service.GoodsService;
public class GoodsController {
    // Get an object used to record the log, so that when printing information, you can mark which kind of information is printed
    private static final Log logger = LogFactory.getLog(GoodsController.class);
    private GoodsService goodsService;
    // The annotation validator is equivalent to "GoodsValidator validator=new GoodsValidator();"
    private Validator validator;
    public String input(Model model) {
        // If there is no goods attribute in the model, addgoods JSP will throw an exception
        // Because the form label cannot find the form backing object specified by the modelAttribute attribute
        model.addAttribute("goods", new Goods());
        return "addGoods";
    public String save(@ModelAttribute Goods goods, BindingResult result,
            Model model) {
        this.validator.validate(goods, result); // Add validation
        if (result.hasErrors()) {
            return "addGoods";
        logger.info("Added successfully");
        model.addAttribute("goodsList", goodsService.getGoods());
        return "goodsList";

8) Write configuration file

Write the configuration file springmvc servlet in the WEB-INF directory XML, the specific code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <!-- Scanning packages using scanning mechanism -->
    <context:component-scan base-package="controller" />
    <context:component-scan base-package="service" />
    <context:component-scan base-package="validator" />
    <!-- Register the format converter because date conversion is used -->
    <bean id="conversionService"
    <!-- Configure view parser -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    <!-- Configure message properties file -->
    <bean id="messageSource"
        <property name="basename" value="/WEB-INF/resource/errorMessages" />

9) Create data display page

Create a data display page goodslist. XML in the WEB-INF/jsp directory jsp. The core code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
            <td>Trade name</td>
            <td>Product details</td>
            <td>commodity price</td>
            <td>Creation date</td>
        <c:forEach items="${goodsList }" var="goods">
                <td>${goods.gname }</td>
                <td>${goods.gdescription }</td>
                <td>${goods.gprice }</td>
                <td>${goods.gdate }</td>

10) Create web XML file

Create a web.inf file in the WEB-INF directory XML file, in which DispatcherServlet, the core controller of Spring MVC, and character encoding filter are configured. The specific code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <!--to configure DispatcherServlet-->
    <!--Avoid Chinese garbled code-->

11) Test application

Release the springMVCDemo08 application and start the Tomcat server, and then pass the address“ http://localhost : 8080/springMVCDemo08/goods/input "test application.

When the input price is greater than 100 yuan, the message "price is 0 ~ 100" will be prompted below, as shown in Figure 3.