input data check spring boot (Validation)


Spring Boot Integration Tutorial


web project, the user's input is always assumed to be unsafe incorrect, before being processed needs to be done check. This article describes the process of implementing data validation in the spring boot project.

Project Description

Implement a simple user registration interface, demonstrates how to perform data validation.

Claim

  • JDK1.8 or later
  • Eclipse development environment

The development environment is not, refer to [spring boot development environment to build (Eclipse)].

Project Creation

Create a spring boot project

Open Eclipse, create spring starter project spring boot of the project, select the menu: File > New > Project ...pop-up dialog box, select: Spring Boot > Spring Starter Projectwhen configuring dependent, check web, complete the project creation.

image

Project Dependencies

The content pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qikegu</groupId>
    <artifactId>springboot-validation-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-validation-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Code

Project directory structure shown below, was added a few classes, will be described below in detail.

image

Create a RegisterRequestclass

When the user registration is required to enter the phone number, password, nickname, create a class to accept front RegisterRequest pass over the data, and check data, parity is achieved by way of comment.


public class RegisterRequest {
    
    @SuppressWarnings("unused")
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(RegisterRequest.class);
    
    @NotNull(message="手机号必须填")
    @Pattern(regexp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", message="账号请输入11位手机号") // 手机号
    private String mobile;
    
    @NotNull(message="昵称必须填")
    @Size(min=1, max=20, message="昵称1~20个字")
    private String nickname;
    
    @NotNull(message="密码必须填")
    @Size(min=6, max=16, message="密码6~16位")
    private String password;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
        
}

Explanation

RegisterRequestClass has three member variables: mobile, , nickname, passwordthese variables are annotated:

  • @NotNull indicates a required
  • @Size string length must comply with the specified range
  • @Pattern input string must match the regular expression

Creating the Controller

We create a AuthControllercontroller class that implements the interface a user registration:

package com.qikegu.demo.controller;

import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qikegu.demo.common.util.MiscUtil;
import com.qikegu.demo.common.util.Result;
import com.qikegu.demo.model.RegisterRequest;

@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces="application/json")
    public ResponseEntity<Result> register(
        @Valid @RequestBody RegisterRequest register, 
        BindingResult bindingResult
    ) {
        if(bindingResult.hasErrors()) { 
            //rfc4918 - 11.2. 422: Unprocessable Entity
//          res.setStatus(422);
//          res.setMessage("输入错误");
//          res.putData("fieldErrors", bindingResult.getFieldErrors());
            
            Result res1 = MiscUtil.getValidateError(bindingResult);
            
            return new ResponseEntity<Result>(res1, HttpStatus.UNPROCESSABLE_ENTITY);
        }
        
        Result res = new Result(200, "ok");
        return ResponseEntity.ok(res);
    }
}

Explanation

The method has two parameters register

  • @Valid @RequestBody RegisterRequest register @RequestBody indicates that the input request from the body, @ Valid indicates that the input for verification when binding
  • BindingResult bindingResult This parameter is stored check results

Auxiliary class MiscUtil, Result

BindingResult returned directly too complicated, a simplified check result using MiscUtil.getValidateError

    static public Result getValidateError(BindingResult bindingResult) {
        
        if(bindingResult.hasErrors() == false) 
            return null;
        
        Map<String,String> fieldErrors = new HashMap<String, String>();
        
        for(FieldError error : bindingResult.getFieldErrors()){
            fieldErrors.put(error.getField(), error.getCode() + "|" + error.getDefaultMessage());
        }
        
        Result ret = new Result(422, "输入错误"); //rfc4918 - 11.2. 422: Unprocessable Entity
        ret.putData("fieldErrors", fieldErrors);
        
        return ret;
    }

Result is the result of the wrapper classes, [spring boot interfaces return value package] has been introduced that one.

run

Eclipse on the left, right click on the project root directory pop-up menu, choose: run as -> spring boot apprun the program. Open Postman access interface, results are as follows:

The input error

image

Enter the correct case

image

to sum up

The complete code

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11014415.html