java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 使用@Validated或@Valid注解校验参数

springboot使用@Validated或@Valid注解校验参数方式

作者:平平常常一般牛

这篇文章主要介绍了springboot使用@Validated或@Valid注解校验参数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

使用@Validated注解校验参数

使用@Validated注解 校验参数是非常简洁和省代码,减少工作量的一种很好用的方式,自用这个注解之前呢,我以前一直用的if判断,这种方式非常麻烦,而且工作量大大加大了。

注解地方

@Validated:可以用在类、方法和方法参数上。

@Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上

嵌套验证

使用@Validated 注解,先在pom文件中加入依赖

<!-- 校验入参 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

使用示例

常用注解

下面的表格列出常用校验类及主要功能。

这些注解必须配合@Valid或@Validated使用,通过这两个注解开启校验。

注 :对于长度的校验基本都支持字符串、集合、Map、数组的长度。

下面是@Valid和@Validated的区别。

注 :嵌套验证。

JavaBean a中某个属性类型是JavaBean b,对a进行验证的同时验证b。

代码示例

在实体类当中定义需要校验的属性参数

@Table
@Entity(name = "person")      // 这是一个标记注释,表明这个类是一个实体。这个注释必须放在类名称上。
@JsonIgnoreProperties(value = "hibernateLazyInitializer")
public class Student implements Serializable {
    @Id      //   此注释位于持有持久标识属性的特定字段上。该字段被视为数据库中的主键。
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    //后端设置名字限制
//    @Column标记表示所持久化属性所映射表中的字段
//      unique属性表示该字段是否为唯一标识
//      nullable属性表示该字段是否可以为null值
    @Column(unique = true, nullable = false)
    @NotBlank(message = "名字不为空")
    @Length(message = "名字长度在1-10之间", min = 1, max = 10)
    private String name;
    //后端设置性别限制
    private int sex;
    @NotBlank(message = "电话不能为空")
    @Length(message = "电话号码长度为4-8", min = 4, max = 11)
    private String telephone;
    @NotBlank(message = "身份证不能为空")
    @Length(message = "电话号码长度为17-18", min = 17, max = 18)
    private String card;
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

在Controller控制器中校验接收参数

 //    添加——接收添加的数据
    @PostMapping("/doAdd")
    @ResponseBody
    public HttpResult doAdd(@Valid Student student){
        serviceStudent.doCreate(student);
        return HttpResult.success();
    }

在postman当中模拟请求校验

{
    "timestamp": "2020-12-20T08:02:27.935+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotBlank.student.telephone",
                "NotBlank.telephone",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "student.telephone",
                        "telephone"
                    ],
                    "arguments": null,
                    "defaultMessage": "telephone",
                    "code": "telephone"
                }
            ],
            "defaultMessage": "电话不能为空",
            "objectName": "student",
            "field": "telephone",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotBlank"
        },
        {
            "codes": [
                "NotBlank.student.card",
                "NotBlank.card",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "student.card",
                        "card"
                    ],
                    "arguments": null,
                    "defaultMessage": "card",
                    "code": "card"
                }
            ],
            "defaultMessage": "身份证不能为空",
            "objectName": "student",
            "field": "card",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotBlank"
        },
        {
            "codes": [
                "NotBlank.student.name",
                "NotBlank.name",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "student.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                }
            ],
            "defaultMessage": "名字不为空",
            "objectName": "student",
            "field": "name",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotBlank"
        }
    ],
    "message": "Validation failed for object='student'. Error count: 3",
    "trace": "org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 3 errors\nField error in object 'student' on field 'telephone': rejected value [null]; codes [NotBlank.student.telephone,NotBlank.telephone,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.telephone,telephone]; arguments []; default message [telephone]]; default message [电话不能为空]\nField error in object 'student' on field 'card': rejected value [null]; codes [NotBlank.student.card,NotBlank.card,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.card,card]; arguments []; default message [card]]; default message [身份证不能为空]\nField error in object 'student' on field 'name': rejected value [null]; codes [NotBlank.student.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.name,name]; arguments []; default message [name]]; default message [名字不为空]\r\n\tat org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n",
    "path": "/student/doAdd"
}

这说明我们的校验已经可以使用了~

总结

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

您可能感兴趣的文章:
阅读全文