zoukankan      html  css  js  c++  java
  • springboot---->springboot中的校验器(一)

      这里面我们简单的学习一下springboot中关于数据格式化的使用。冬天花败,春暖花开,有人离去,有人归来。

    springboot中的校验器

    我们的测试环境是springboot,对请求的person数据先做转换再校验。

    一、我们定义的实体Bean类Person

    package com.linux.huhx.learn.converter;
    
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    import java.io.Serializable;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 3:30
     * @Desc: 实体类
     */
    public class Person implements Serializable {
        @NotNull(message = "用户名不能为空")
        @Size(min = 3, message = "用户名的长度小于3位")
        private String username;
        private String password;
    
        @Min(value = 18, message = "用户的年龄不能小于18")
        private int age;
    
        public Person(String username, String password, int age) {
            this.username = username;
            this.password = password;
            this.age = age;
        }
    
      // ..get set
    }

    二、我们的检验控制器类

    package com.linux.huhx.learn.converter;
    
    import com.linux.huhx.exception.MaxRunTimeException;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.ObjectError;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.validation.Valid;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 3:46
     * @Desc: 测试springboot中自定义类型转换器
     */
    
    @RestController
    @RequestMapping("/converter")
    public class PersonConverterAction {
    
        @PostMapping("/person")
        public Person convertrStringToPerson(@Valid Person person, BindingResult bindingResult) {
            if (bindingResult.hasErrors()) {
                for (ObjectError error : bindingResult.getAllErrors()) {
                    throw new MaxRunTimeException(error.getDefaultMessage());
                }
            }
            return person;
        }
    }

    通过postman发送post的请求:http://localhost:9998/converter/person。

    返回的数据:

    {
        "timestamp": 1513336242870,
        "status": 500,
        "error": "Internal Server Error",
        "exception": "com.linux.huhx.exception.MaxRunTimeException",
        "message": "用户的年龄不能小于18",
        "path": "/converter/person"
    }

    友情链接

  • 相关阅读:
    如何使用ASP.NET2.0的“嵌入的资源”
    多核心计算机运算
    [翻译]注册协议(Register Protocol)
    [翻译]关于“异步可插协议”(About Asynchronous Pluggable Protocols(APPs))
    [ASP.NET]runat="server" causes the problem (< or &lt;)
    [翻译]将应用程序注册为URL协议(Registering an Application to a URL Protocol)
    【C# 转换编码格式】 唉,总是忘记的一个方法。
    在WinForm中借助WebBrowser控件使用 tinymce 总结
    sqlite 资料整理(一)
    sqlite 性能优化
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootvalidate1.html
Copyright © 2011-2022 走看看