zoukankan      html  css  js  c++  java
  • 数据校验工具类

    思路,

     1、传入要校验的属性以及如果校验不过提示信息

     2、如果数据校验不过返回json 格式信息。

     3、不满足条件抛出自定义异常,然后在异常处理器中获取信息,return 信息

    一、自定义异常

    public class LyonException extends RuntimeException{
        private static final long serialVersionUID = 1L;
        
        private String msg;
        private int code = 500;
        code 默认是500
        public LyonException(String msg) {
            super(msg);
            this.msg = msg;
        }

        public LyonException(String msg, int code) {
           super(msg);
           this.msg = msg;
           this.code = code;
       }

     

    二、异常处理器

    /**
     * 异常处理器
     * @author    lyon
     * @date    2018年3月2日
     */
    @RestControllerAdvice
    public class LyonExceptionHandler {
    
        
        @ExceptionHandler(LyonException.class)
        public R handlerLyonException(LyonException e){
            R r = new R();
            r.put("code", e.getCode());
            r.put("msg", e.getMessage());
            return r;
        }
    }

    三、返回值R

    public class R extends HashMap<String, Object> {
        private static final long serialVersionUID = 1L;
    
        public R() {
            put("code", 0);
            put("msg", "操作成功");
        }
    
        public static R error() {
            return error(1, "操作失败");
        }
    
        public static R error(String msg) {
            return error(500, msg);
        }
    
        public static R error(int code, String msg) {
            R r = new R();
            r.put("code", code);
            r.put("msg", msg);
            return r;
        }
    
        public static R ok(String msg) {
            R r = new R();
            r.put("msg", msg);
            return r;
        }
    View Code

    四、工具类

    /**
     * 数据校验
     * @author    lyon
     * @date    2018年3月2日
     */
    public abstract class Assert {
    
        /**
         * @param str 校验的字符串
         * @param msg 提示信息
         */
        public static void isBlank(String str,String msg){
            if(StringUtils.isBlank(str)){
                throw new LyonException(msg);
            }
        }
        
        public static void isNull(Object object, String message) {
            if (object == null) {
                throw new LyonException(message);
            }
        }
    }

    五、测试

        @GetMapping("/test")
        @ResponseBody
        public R hello(String name) {
            Assert.isBlank(name, "用户名不能为空");
            return R.ok();
        }

  • 相关阅读:
    声明式事务
    AOP面向切面编程笔记
    IOC容器和Bean的配置实例
    IOC容器和Bean的配置
    nlogn的最长不下降子序列【tyvj1254挑选士兵】
    POJ1703 Find them, Catch them
    [code]poj3349 Snowflake Snow Snowflakes
    hdu 4607 Park Visit 树的直径
    hdu 1520 Anniversary party
    hdu 4863 Centroid of a Tree 树dp
  • 原文地址:https://www.cnblogs.com/lyon91/p/8492355.html
Copyright © 2011-2022 走看看