好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用@RequestBody配合@Valid校验入参参数

@RequestBody配合@Valid校验入参参数

自定义一个Controller

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import com.example.demo.pojo.User;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController; 

import javax.validation.Valid;

/**

  * @Author: luoye

  * @Date: 2018-10-12

  */

@RestController

public class ValiController {

    @PostMapping (value = "/" ,produces = "application/json;charset=UTF-8" )

    public User vali( @RequestBody @Valid User user){

        return user;

    }

}

自定义实体类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import javax.validation.constraints.Max;

import javax.validation.constraints.NotBlank;

import javax.validation.constraints.NotNull;

 

/**

  * @Author: luoye

  * @Date: 2018-10-12

  */

public class User {

    @NotBlank (message = "这个姓名不能为空" )

    private String name;

    @NotNull (message = "这个年龄不能为空" )

    @Max (value = 105 ,message = "太大了" )

    private Integer age;

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this .name = name;

    }

 

    public Integer getAge() {

        return age;

    }

 

    public void setAge(Integer age) {

        this .age = age;

    }

}

自定义全局异常处理器

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

import com.example.demo.pojo.ErrorMsg;

import org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.validation.ObjectError;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ResponseBody;

 

import java.util.ArrayList;

import java.util.List;

 

/**

  * @Author luoye

  * @Date: 2018/10/12 16:50

  */

@ControllerAdvice

public class ExceptionHandlerContrller { 

 

    @ExceptionHandler (MethodArgumentNotValidException. class )

    @ResponseBody

    public List<ErrorMsg> exception(MethodArgumentNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();

        List<ObjectError> allErrors = bindingResult.getAllErrors();

        List<ErrorMsg> errorMsgs = new ArrayList<>();

 

        allErrors.forEach(objectError -> {

            ErrorMsg errorMsg = new ErrorMsg();

            FieldError fieldError = (FieldError)objectError;

            errorMsg.setField(fieldError.getField());

            errorMsg.setObjectName(fieldError.getObjectName());

            errorMsg.setMessage(fieldError.getDefaultMessage());

            errorMsgs.add(errorMsg);

        });

        return errorMsgs;

    }

}

PostMan测试下

?

1

2

3

4

5

6

7

8

9

10

11

12

[

    {

        "field" : "name" ,

        "message" : "这个姓名不能为空" ,

        "objectName" : "user"

    },

    {

        "field" : "age" ,

        "message" : "这个年龄不能为空" ,

        "objectName" : "user"

    }

]

附录

@Valid 注解类型的使用:

@Null :限制只能为null @NotNull :限制必须不为null @AssertFalse :限制必须为false @AssertTrue :限制必须为true @DecimalMax(value) :限制必须为一个不大于指定值的数字 @DecimalMin(value) :限制必须为一个不小于指定值的数字 @Digits(integer,fraction) :限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction @Future :限制必须是一个将来的日期 @Max(value) :限制必须为一个不大于指定值的数字 @Min(value) :限制必须为一个不小于指定值的数字 @Past :限制必须是一个过去的日期 @Pattern(value) :限制必须符合指定的正则表达式 @Size(max,min) :限制字符长度必须在min到max之间 @Past :验证注解的元素值(日期类型)比当前时间早 @NotEmpty :验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) @NotBlank :验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 @Email :验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

@Valid校验@RequestBody的参数

希望通过注解校验post请求的body

需要用到@Valid注解

?

1

2

3

public String getResponse( @RequestBody @Valid MyRequest request) throws Exception {

     xxx

}

在request实体类添加注解进行校验

例如用@NotNull进行判空校验

?

1

2

3

4

5

6

7

@Data

public class MyRequest {

     @NotNull (message = "id 不能为空" )

     private Integer id;

     @NotNull (message = "name 不能为空" )

     private String name;

}

结合统一异常处理,处理MethodArgumentNotValidException

可以返回注解配置的错误信息

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

@ControllerAdvice

@Slf4j

public class ExceptionResolver {

     @ExceptionHandler (value = {Exception. class })

     @ResponseBody

     public String handleOtherExceptions( final Exception ex) {

         if (ex instanceof MethodArgumentNotValidException) {

             // 入参校验错误

             StringBuilder msg = new StringBuilder();

             MethodArgumentNotValidException mex = (MethodArgumentNotValidException) ex;

             BindingResult bindingResult = mex.getBindingResult();

             List<ObjectError> allErrors = bindingResult.getAllErrors();

             allErrors.forEach(objectError -> {

                 FieldError fieldError = (FieldError) objectError;

                 String oneMsg = fieldError.getDefaultMessage();

                 msg.append(oneMsg);

                 msg.append( ";" );

             });

             return msg.toString();

         }

     }

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/lzhcoder/article/details/98870852

查看更多关于使用@RequestBody配合@Valid校验入参参数的详细内容...

  阅读:22次