Java参数校验

你的项目中是否用到参数校验呢,还是说你就没有考虑入参为空的情况。今天教大家基于SpringBoot的注解来判断入参是否正确。

1、首先创建项目所需的Bean

package com.ifilldream.check_lean.demo.bean;

import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * @author RickSun  && iFilldream
 */
@Data
public class User {
    //message可以表达的再委婉一点,小编就直接刚了
    @NotNull ( message = "用户姓名不得为null")
    @NotEmpty( message = "用户姓名不得为空")
    private String name;

    @NotNull ( message = "用户年龄不得为空")
    @Max(value = 130,message = "年龄不得大于130岁")
    @Max(value = 1,message = "年龄不得小于1岁")
    private Integer age;

    @NotNull ( message = "用户手机不得为null")
    @NotEmpty( message = "用户手机不得为空")
    @Length( min = 11,max = 11,message = "用户手机长度必须为11位")
    private String telephone;

}

2、创建Controller

package com.ifilldream.check_lean.demo.controller;

import com.ifilldream.check_lean.demo.bean.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author RickSun  && iFilldream
 */
@RestController()
@RequestMapping("/ifilldream/user")
public class CheckController {

    @PostMapping("/add")
    public String addUser(@RequestBody @Valid User user){
        //Do something
        return "ok";
    }

}

注意,此处一定要加入@Valid注解用于验证。

3、测试效果

file我们可以看到错误提示是非常详细的,但是这种返回格式并不是我们想要的,此时就需要统一拦截处理,转换成项目所需的返回格式了。

4、配置拦截

package com.ifilldream.check_lean.demo.filter;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author RickSun  && iFilldream
 */
@ControllerAdvice
@ResponseBody
public class ErrorHandler {
    @ExceptionHandler(Exception.class)
    public String handleExption(Exception e){
        String msg = null;
        if(e instanceof MethodArgumentNotValidException) {
            //将具体的错误提示提取出来
            msg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        }else {
            msg =  e.getMessage();
        }
        return msg;
    }
}

file此处返回的是String,可以根据改成项目统一的返回类。有人就会问了,这个方法的反射效率会不会很低,其实并不低的,可以放心使用。这里只简单的介绍了入参校验,更多校验请参考以下注解:

@Null  被注释的元素必须为null
@NotNull  被注释的元素不能为null
@AssertTrue  被注释的元素必须为true
@AssertFalse  被注释的元素必须为false
@Min(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min)  被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction)  被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past  被注释的元素必须是一个过去的日期
@Future  被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty  被注释的字符串必须非空
@Range  被注释的元素必须在合适的范围内

统一首发平台为微信公众号"轻梦致新",搜索关注公众号,第一时间阅读最新内容。

发布了6 篇原创文章 · 获赞 2 · 访问量 661

猜你喜欢

转载自blog.csdn.net/RickSunLee/article/details/103979218