Spring MVC: data binding

Insert image description here

data binding

Data binding refers to the object binding between the request and response data on the Web page and the corresponding processing method in the Controller (that is, binding the form data submitted by the user into a Java object).

Insert image description here

The process is as follows:

  1. The ServletRequest object is passed to the WebDataBinderFactory object
  2. At the same time, the input parameter object of the target method will also be passed to the WebDataBinderFactory object. The WebDataBinderFactory object will create a DataBinder object based on the passed parameters.
  3. The DataBinder object will call the ConversionService component to perform data type conversion or formatting, and then fill the request information in the Servlet into the input parameter object on the corresponding processing method in the Controller.
  4. The DataBinder object then calls the Validator component to verify the data validity of the input parameter object of the bound request information, and generates the data binding result BindingResult object.
  5. The verification results are stored in the BindingResult object, and the DataBinder object can assign them to the corresponding input parameters of the processing method.

Data type conversion

The requested data and response data require data type conversion. The ConversionService component of Spring MVC contains many built-in converters of Spring MVC, which can complete most of the Java type conversion work. Of course, you can also create a custom converter and use ConversionServiceFactoryBean to define a ConversionService in the Spring IoC container. Spring will automatically recognize the custom ConversionService and automatically call the custom converter to perform data type conversion in the Bean property configuration and the input parameter binding data of the Spring MVC processing method.

Data formatting

Typically, data formatting is used to convert string types to date types.

Simple example:
Based on the integration case of Spring + Spring MVC + JDBCTemplate in the previous chapter, add the date attribute of the object and implement the added function

1. Use the @DateTimeFormat(pattern = “yyyy-MM-dd”) annotation to convert the string type into a date type.
Insert image description here
Add the method implementation class as shown in the figure:
Insert image description here

Add user information in the controller layer through RESTful style

package cn.edu.springmvcdemo.controller;

import cn.edu.springmvcdemo.model.User;
import cn.edu.springmvcdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class UserController {
    
    
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public String getSelectAll(Model model){
    
    
        //查看
        List<User> users = userService.selectAll();
        model.addAttribute("users",users);

        //新增
        model.addAttribute("user",new User());
        return "user";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(User user){
    
    
        userService.add(user);
        return "redirect:/users";
    }
}

Add the following content in user.jsp

<br><br><br>
<form:form action="${pageContext.request.contextPath}/user" method="post" modelAttribute="user">
    用户姓名:<form:input path="name" /> <br>
    用户年龄:<form:input path="age" /> <br>
    用户班级:<form:input path="grade" /> <br>
    入学日期:<form:input path="date" /> <br>
    <input type="submit" value="添加">
</form:form>

In addition, in order to prevent Chinese garbled characters, the following configuration needs to be added to the web.xml configuration file

<!-- 防止出现中文乱码配置 -->
<filter>
  <filter-name>encoding</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>
</filter>
<filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Also, the date data can be obtained normally when passed from the front end to the back end, but the difference will be one day after the back end inserts it into the database. In the jdbc.properties configuration file, change serverTimezone=UTC to serverTimezone=Asia/Shanghai. Note
Insert image description here
: UTC is the world unified time, which is 8 hours earlier than Beijing time.

The result is as shown below:
Insert image description here

2. Create a general data formatting class annotated with @InitBinder. The controller class that needs date formatting can inherit it.

package cn.edu.springmvcdemo.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;

//设置数据格式化通用类
public class CurrencyController {
    
    
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
    
    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //设定为合法的日期格式
        simpleDateFormat.setLenient(false);
        //注册到编辑器中
        webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(simpleDateFormat,false));
    }
}

Others remain unchanged, the controller class inherits the general data formatting class and annotation @DateTimeFormat(pattern = “yyyy-MM-dd”) annotation
Insert image description here
Insert image description here

The result is as shown below:
Insert image description here

Data validation

Data verification is a verification operation performed to ensure data integrity. The following is a brief introduction to using JSR-303 for verification.

JSR-303 (Java Specification Requests, Java specification proposal) is a Java standard verification framework. The verification of JSR-303 is based on annotations. Annotation tags will be automatically verified after the attributes or get() methods of the entity classes that need to be verified.

Commonly used verification annotations

annotation illustrate
@Null Empty check. Verify object is NULL
@NotNull Empty check. Verify that the object is not NULL, cannot check for a string of length 0
@NotBlank Empty check. Check whether the constraint string is NULL and whether the length of spaces before and after deletion is greater than 0
@NotEmpty Empty check. Check whether the constraint element is NULL or EMPTY
@Past Date check. Verify whether the Date and Calendar objects are before the current time (the time passed must be in the past)
@Future Date check. Verify whether the Date and Calendar objects are after the current time (the time passed must be in the future)
@DecimalMax Numerical check. The value that passes the verification will not be greater than the maximum value specified in the constraint, and there is precision for decimals
@DecimalMin Numerical check. The value that passes the verification will not be less than the minimum value specified in the constraint, and there is precision for decimals
@Email Numerical check. Verify if it is an email address. If it is NULL, it can pass without verification.

Simple example:
perform data verification based on the user case added above

First, add the following dependencies in pom.xml

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.2.5.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator-annotation-processor -->
<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator-annotation-processor</artifactId>
  <version>6.2.5.Final</version>
</dependency>

Next, add verification annotations to the attributes of the entity class
Insert image description here

Then, use the @Valid annotation before adding parameters on the user method of the controller class, and use the BindingResult object to obtain the verification result.

@RequestMapping(value = "/user",method = RequestMethod.POST)
//注:这两个参数必须紧靠着(即当有第三个参数时,第三个参数不能放在这两个参数的中间)
public String addUser(@Valid User user, BindingResult bindingResult,Model model){
    
    
    //当不符合数据校验时,结果存放在 bindingResult 中
    if(bindingResult.getErrorCount() > 0){
    
    
        //遍历获取
        for (FieldError fieldError:bindingResult.getFieldErrors()){
    
    
            System.out.println("校验结果 == " + fieldError.getField() + ":" + fieldError.getDefaultMessage());
        }
        //添加数据不符,不作添加并返回
        //查看
        List<User> users = userService.selectAll();
        model.addAttribute("users",users);
        return "user";
    }

    userService.add(user);
    return "redirect:/users";
}

Subsequently, use the <form:errors> tag on user.jsp to echo the verification results .

<form:form action="${pageContext.request.contextPath}/user" method="post" modelAttribute="user">
    用户姓名:<form:input path="name" /> <form:errors path="name" /> <br>
    用户年龄:<form:input path="age" /> <form:errors path="age" /> <br>
    用户班级:<form:input path="grade" /> <form:errors path="grade" /> <br>
    入学日期:<form:input path="date" /> <form:errors path="date" /> <br>
    <input type="submit" value="添加">
</form:form>

Finally, the test results
are as follows:
Insert image description here

Insert image description here

Generally, the default verification results can be used for echoing. Of course, you can also customize the echo information.

1. Just use the message attribute in the verification annotation, but the English result cannot be customized to be echoed.
Insert image description here
Insert image description here

2. Use the internationalization configuration file to configure custom echo information.
Based on the case of configuring the internationalization resource file in the article Spring MVC: Views and View Parsers, add the following content under the i18n.properties configuration file.
Note: Usually annotations. name + the first letter of the entity class name in lowercase + the attribute name; when the data type conversion error message is typeMismatch + the first letter of the entity class name in lowercase + the attribute name

NotEmpty.user.grade=国际化资源文件配置结果:该信息不能为空
typeMismatch.user.date=国际化资源文件配置结果:该信息不能为空

The result is as shown below:
Insert image description here

attached

In Spring MVC, the @RequestBody and @ResponseBody annotations are often used in the Controller layer to directly use Java objects as request parameters and return content in the Controller layer. The following implements JSON data return.

Simple example:
First, add the following dependencies in pom.xml

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.12.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.12.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.12.0</version>
</dependency>

Next, add the following method to the controller class

@RequestMapping(value = "jsonViewTest")
public String jsonViewTest(){
    
    
    return "json";
}

@ResponseBody
@RequestMapping(value = "jsonTest",method = RequestMethod.GET)
public List<User> jsonTest(){
    
    
    List<User> users = userService.selectAll();
    System.out.println(users);
    return users;
}

Then, create json.jsp. At the same time, import the jquery-2.1.2.js file in the src\main\webapp\resources\js\jquery directory ( click to download to get it )

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2023/8/8
  Time: 15:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery/jquery-2.1.2.js" />
    <script type="text/javascript">
        $(function () {
      
      
            $("#jsonid").click(function(){
      
      
                var href = this.href;
                var args = {
      
      };
                $.post(href,args,function (data) {
      
      
                    alert(data);
                })
                return false;
        })
    </script>
</head>
<body>
    <a id="jsonid" href="${pageContext.request.contextPath}/jsonTest" >
        获取 json 数据格式的所有用户信息
    </a>
</body>
</html>

Finally, test results
1. Click to get
Insert image description here
2. The results are as shown below:
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_56886142/article/details/132094309