码迷,mamicode.com
首页 > 编程语言 > 详细

springboot实现注解参数校验

时间:2021-06-16 18:19:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:epo   bad   entity   info   script   frame   hang   https   模型   

引入依赖

说明:springboot版本2.30.RELEASE,必须要引入的是spring-boot-starter-web/webflux, spring-boot-starter-validation, lombok是一个工具包可以通过注解生成get/set构造 sl4j等;
本文代码,使用的webflux,集成mongodb的实现

<?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 https://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.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhou.webflux.example</groupId>
    <artifactId>webflux-mvc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webflux-mvc</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</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>
        <!-- springboot2.30以上版本需要手动导入,之前的版本只需引入spring-boot-starter-web/webflux -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

pojo模型

在需要校验字段需要增加valuation注解

package com.zhou.webflux.example.webfluxmvc.domain;

import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.validation.constraints.NotBlank;

@Data
@Document(collection = "user")
public class User {
    @Id
    private String id;
    //不为空校验注解
    @NotBlank
    private String name;
    //数据范围注解
    @Range(min=10,max = 80,message = "age在10到80之间")
    private int age;

}

controller

在需要校验的形参前加入 @Valid注解

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserRepository repository;

    @PostMapping("")
    public Mono<User> createUser(@Valid @RequestBody User user) {
        //save update公用一个方法 有id修改 无id新增
        return this.repository.save(user);
    }
}

编写springboot全局异常处理类处理参数异常

@ControllerAdvice
public class CheckAdvice {
    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity handleBindException(WebExchangeBindException e){
        return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    private String toStr(WebExchangeBindException ex){
        return ex.getFieldErrors().stream().map(e -> e.getField() + ":" + e.getDefaultMessage())
                .reduce("", (s1, s2) -> s1 + "\n" + s2);
    }
}

演示

技术图片
技术图片

springboot实现注解参数校验

标签:epo   bad   entity   info   script   frame   hang   https   模型   

原文地址:https://www.cnblogs.com/zw-habbit/p/14889052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!