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"
    pageEncoding="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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add item</title>
</head>
<body>
    <form:form modelAttribute="goods"
        action="${pageContext.request. contextPath }/goods/save" method="post">
        <fieldset>
            <legend> Add an item </legend>
            <P>
                <label>Trade name:</label>
                <form:input path="gname" />
            </p>
            <p>
                <label>Product details:</label>
                <form:input path="gdescription" />
            </p>
            <P>
                <label>commodity price:</label>
                <form:input path="gprice" />
            </p>
            <P>
                <label>Creation date:</label>
                <form:input path="gdate" />
                (yyyy-MM-dd)
            </p>
            <p id="buttons">
                <input id="reset" type="reset">
                <input id="submit" type="submit" value="add to">
            </p>
        </fieldset>
        <!-- Remove all validation errors -->
        <form:errors path="*" />
    </form:form>
</body>
</html>

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;
@Component
public class GoodsValidator implements Validator {
    @Override
    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);
    }
    @Override
    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",
                "goods.gdescription.required");
        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:

goods.gname.required=\u8BF7\u8F93\u5165\u5546\u54C1\u540D\u79F0
goods.gdescription.required=\u8BF7\u8F93\u5165\u5546\u54C1\u8BE6\u60C5
gprice.invalid=\u4EF7\u683C\u4E3A0~100
gdate.invalid=\u521B\u5EFA\u65E5\u671F\u4E0D\u80FD\u5728\u7CFB\u7EDF\u65E5\u671F\u4E4B\u540E

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"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/resource/errorMessages" />
</bean>

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;
@Service
public class GoodsServiceImpl implements GoodsService {
    // Simulate the database with the static set variable goods
    private static ArrayList<Goods> goods = new ArrayList<Goods>();
    @Override
    public boolean save(Goods g) {
        goods.add(g);
        return true;
    }
    @Override
    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;
@Controller
@RequestMapping("/goods")
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);
    @Autowired
    private GoodsService goodsService;
    // The annotation validator is equivalent to "GoodsValidator validator=new GoodsValidator();"
    @Resource
    private Validator validator;
    @RequestMapping("/input")
    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";
    }
    @RequestMapping("/save")
    public String save(@ModelAttribute Goods goods, BindingResult result,
            Model model) {
        this.validator.validate(goods, result); // Add validation
        if (result.hasErrors()) {
            return "addGoods";
        }
        goodsService.save(goods);
        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"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
    <!-- 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"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    </bean>
    <!-- Configure view parser -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- Configure message properties file -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/resource/errorMessages" />
    </bean>
</beans>

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"
    pageEncoding="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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table>
        <tr>
            <td>Trade name</td>
            <td>Product details</td>
            <td>commodity price</td>
            <td>Creation date</td>
        </tr>
        <c:forEach items="${goodsList }" var="goods">
            <tr>
                <td>${goods.gname }</td>
                <td>${goods.gdescription }</td>
                <td>${goods.gprice }</td>
                <td>${goods.gdate }</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

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" 
    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" version="3.0">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--Avoid Chinese garbled code-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
             org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

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.