亲宝软件园·资讯

展开

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

击水三千里 人气:0

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

自定义一个Controller

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;
    }
}

自定义实体类

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;
    }
}

自定义全局异常处理器

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测试下

[
    {
        "field": "name",
        "message": "这个姓名不能为空",
        "objectName": "user"
    },
    {
        "field": "age",
        "message": "这个年龄不能为空",
        "objectName": "user"
    }
]

附录

@Valid 注解类型的使用:

@Valid校验@RequestBody的参数

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

需要用到@Valid注解

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

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

例如用@NotNull进行判空校验

@Data
public class MyRequest {
    @NotNull(message = "id 不能为空")
    private Integer id;
    @NotNull(message = "name 不能为空")
    private String name;
}

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

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

@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();
        } 
    }
}

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

加载全部内容

相关教程
猜你喜欢
用户评论