项目代码已上传到gitLab上面,

地址为:

https地址:https://gitlab.com/open_sources/blog_cloud.git

ssh地址:git@gitlab.com:open_sources/blog_cloud.git

通过上一章《SpringCloud开发个人博客项目(框架搭建)》,可以搭建出一个springCloud的项目雏形,今天将项目使用到的公共类做一个编码,主要涉及到项目公共返回参数、全局异常处理类、工具类、校验器、静态常量、接口返回规则等的定义,在自己实际开发过程中,可以根据自己的需求,自己添加相应代码,这节主要是做一个common类的基本架子,后面在开发过程中,我们户会添加更多的公共方法、参数等,下面进入本节的主题。

1. 公共返回参数

在建好的的项目模块common下添加enums包,然后创建枚举类CommonReturnParameter,如下图:

按照上图添加返回参数规则,目前代码如下:

package com.blog.common.enums;

import lombok.Getter;

/**
 * <p>Title: CommonReturnParameter</p >
 * <p>Description: 接口请求公共返回参数定义,在开中严格按照此状态码、状态说明返回</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/4 22:26
 * @Version: 1.0
 */
@Getter
public enum CommonReturnParameter {

    //通用操作成功code  2001XX
    REQUEST_SUCCESS(200100, "请求成功"),
    OPERATE_SUCCESS(200101, "操作成功"),
    UPLOAD_SUCCESS(200102, "文件上传成功"),
    UPDATE_SUCCESS(200103, "更新成功"),

    //通用的操作错误码  5001XX
    REQUEST_FAILD(500100, "请求失败"),
    OPERATE_FAILD(500101, "操作失败"),
    UPLOAD_FAILD(500102, "文件上传失败"),
    UPDATE_FAILD(500103, "更新失败"),
    SYSTEM_ERROR(5001, "系统错误"),
    PARAMETER_ERROR(500104, "参数错误"),

    //登录模块返回码 5002XX
    SESSION_ERROR(500201, "Session不存在或者已经失效"),
    PASSWORD_EMPTY(500202, "登录密码不能为空"),
    MOBILE_EMPTY (500203, "手机号不能为空"),
    MOBILE_ERROR(500204, "手机号格式错误"),
    MOBILE_NOT_EXIST(500205, "手机号不存在"),
    PASSWORD_ERROR(500206, "密码错误"),
    ACCOUNT_EMPTY(500207, "账号不能为空"),
    ACCOUTN_IS_NOT_EXIST(500208, "账号不存在"),
    ;

    private Integer code;

    private String message;

    CommonReturnParameter(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

提示:这里使用到了lombok这个依赖,在idea中第一次使用lombok的时候,会报编译错误,这是因为idea需要装lombok的plugin,具体过程如下图:

进去之后,搜索plugins,然后在插件安装里面搜索lombok安装,如下图:

因为我已经安装过了,所以界面是上面这样的,具体插件安装,如果不清楚可以网上查找资料,有很多不错的文章。

2. 全局异常处理类

系统所有的异常处理,都通过这个类定义的规则去返回,如下图:

代码如下:

package com.blog.common.exception;

import com.blog.common.enums.CommonReturnParameter;

/**
 * <p>Title: CommonException</p >
 * <p>Description: 公共异常处理类</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/4 22:24
 * @Version: 1.0
 */
public class CommonException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private Integer code;


    public CommonException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public CommonException(CommonReturnParameter commonReturnParameter) {
        super(commonReturnParameter.getMessage());
        this.code = commonReturnParameter.getCode();
    }
}

至于怎么使用,在后面写接口代码的时候,会有实际的代码演示,当然这个异常处理类不完善,只是写了一个简单的自定义异常处理,后面会一步一步完善。

3. 工具类

3.1 UUID转换工具

在实际开发中,我们会用到java的util包提供的UUID,但是UUID是用"-"分割的,我这里做了一个工具类将"-"去掉,代码如下:

package com.blog.common.utils;

import java.util.UUID;

/**
 * <p>Title: UUIDUtil</p >
 * <p>Description: uuid转换</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/4 22:21
 * @Version: 1.0
 */
public class UUIDUtil {
    /**
     * @description: uuid转换,将默认的"-"转换为""
     * @auther: qiwei
     * @date: 2019/7/21 22:20
     * @return:
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

3.2 手机号码校验工具

这里先简单写一个手机号码校验工具,后面遇到复杂的校验我们再一步一步完善,如下图:

具体代码:

package com.blog.common.utils;

import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Title: ValidatorUtil</p >
 * <p>Description: 校验工具类</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/6 20:55
 * @Version: 1.0
 */
public class ValidatorUtil {

    //手机号码校验正则
    private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");

    /**
     * @description: 手机号码校验方法
     * @auther: qiwei
     * @date: 2019/8/6 20:56
     * @param cellPhone 手机号码
     * @return: boolean
     */
    public static boolean isMobile(String cellPhone) {
        if(StringUtils.isEmpty(cellPhone)) {
            return false;
        }
        Matcher matcher = mobile_pattern.matcher(cellPhone);
        return matcher.matches();
    }
}

3.3 手机号码校验注解自定义

在3.2我们看到可以使用方法校验一个手机号码是否合法,我们现在使用注解,对手机号码校验这个使用频率比较高的校验类做一个高级写法。<这里先使用注解做一个例子,后面对java里面的自定义注解,我会专门做一个分享专题,想了解的小伙伴关注公众号就行,写完我会及时推送给大家>。

注:在使用自定义注解的时候,我们这里使用到validation依赖的@Constraint注解,所以需要在项目引入这个依赖,如下:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
 </dependency>

下面是校验注解的写法,如图:

具体代码:

package com.blog.common.validator;

import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * <p>Title: IsMobile</p >
 * <p>Description: 手机号码校验注解定义</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/6 21:04
 * @Version: 1.0
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {

    boolean required() default true;

    String message() default "手机号码格式错误";

}

校验依据类定义如图:

具体代码如下:

package com.blog.common.validator;

import com.blog.common.utils.ValidatorUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * <p>Title: IsMobileValidator</p >
 * <p>Description: 手机号码校验器,供IsNobile注解使用</p >
 * <p>Company: http://www.yinjiedu.com</p >
 * <p>Project: blog_cloud</p >
 *
 * @author: qiwei
 * @Date: 2019/8/6 21:09
 * @Version: 1.0
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p/>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p/>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(required) {
            return ValidatorUtil.isMobile(value);
        }else {
            if(StringUtils.isEmpty(value)) {
                return true;
            }else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}

目前common公共类暂时就定义这么几个,后面在开发过程中我们慢慢完善,有兴趣的朋友可以一起参与进来。项目代码全部上传到git!

获取实时信息,关注公众号:『编程之艺术』,二维码:

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐