java常用知识点

174 阅读8分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

转码

Base64Utils.encodeToString("");  //转化为base64编码

前端入值判空

VO实体

在接受前端实体的VO的属性上添加注解 message 为 提示的信息

@NotNull(message = "不能为空")  验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank(message = "不能为空") 检查约束 (字符串) 是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty(message = "不能为空") 检查(集合)约束元素是否为NULL或者是EMPTY.

controller

    @ApiOperation("修改面试官的评价")
    @PostMapping("/update/interviewEvaluation")
    public Result updateInterviewEvaluation(@RequestBody @Valid InterviewEvaluationVo interviewEvaluationVo, BindingResult validResult) {
        //BindingResult 为springframework自带工具类
        log.info("修改面试官的评价的入参为: {}", JSONObject.toJSONString(interviewEvaluationVo));
        if(validResult.hasErrors()){
            log.error("修改面试官评价 {}",validResult.getFieldError().getDefaultMessage());
            return Result.failure().setMessage(validResult.getFieldError().getDefaultMessage());
        }
        try {
            return interviewEvaluationService.updateInterviewEvaluation(interviewEvaluationVo);
        } catch (Exception e) {
            log.error("*****修改面试官的评价-异常 {}", e);
            return Result.failure();
        }
    }

当前日期格式化

String imgRealPath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

主键回显

   @GeneratedValue(strategy = GenerationType.IDENTITY)

集合去重

方式一:根据对象的一个属性

        ArrayList<Person> collect = people.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(
                                Person::getId))), ArrayList::new));

方式二:根据对象的多个属性

        ArrayList<Person> collect = people.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(
                                p -> p.getId() + ";" + p.getName()))), ArrayList::new));
​

IntStream

方法说明
rangeClosed(a,b)返回子序列 [a,b),左闭又开。意味着包括 b 元素,增长步值为 1
range(a,b)返回子序列 [a,b),左闭右开,意味着不包括 b
sum计算所有元素的总和
sorted排序元素

文件上传

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
​
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
​
@Slf4j
public class FileUploadUtils {
​
    /**
     * 上传文件
     * @param multipartFile
     * @param uploadPath
     * @param fileName
     * @throws Exception
     */
    public static Boolean uploadFiles(MultipartFile multipartFile,String uploadPath,String fileName){
        if(StringUtils.isEmpty(uploadPath) || StringUtils.isEmpty(fileName)){
            return false;
        }
​
        File file = null;
        try {
            //创建文件夹路径
            file = new File(uploadPath);
            if (!file.exists()) {
                file.mkdirs();
            }
​
            //读取新文件
            File writeFile = new File(uploadPath + fileName);
​
            //文件写入磁盘
            multipartFile.transferTo(writeFile);
            log.info("图片上传成功!");
            return true;
        }catch (Exception e){
            log.error("*****图片上传失败:",e.getMessage());
        }
        return false;
    }
​
    public static void delImg(String[] path){
        File file = null;
        try{
            for(String s:path){
                file = new File(s);
                if(file.exists()){
                    log.info("*****图片删除成功***");
                    file.delete();
                }
            }
        }catch (Exception e){
            log.error("*****图片删除失败:",e);
        }
    }
​
​
    /**
     * 将base64码解析成文件上传指定位置
     * @param base64
     * @param filePath
     * @return
     */
    public static boolean decryptByBase64(String base64, String filePath) {
        if (base64 == null && filePath == null) {
            log.info("上传文件失败!!");
            return false;
        }
​
        try {
            byte[] decode = Base64.getDecoder().decode(base64);
            FileUtils.writeByteArrayToFile(new File(filePath), decode);
        } catch (IOException e) {
            log.error("上传文件失败!!:{}",e);
            return false;
        }
        return true;
    }
​
    /**
     * 上传文件
     * @param multipartFile
     * @param uploadPath
     * @param fileName
     * @throws Exception
     */
    public static Boolean uploadFilesToAuth(MultipartFile multipartFile,String uploadPath,String fileName) throws Exception{
        if(StringUtils.isEmpty(uploadPath) || StringUtils.isEmpty(fileName)){
            return false;
        }
​
        log.info("上传文件路径:{},文件名称:{}",uploadPath,fileName);
​
        //创建文件夹路径
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
​
        //获取文件字节数组
        byte [] bytes = multipartFile.getBytes();
​
        //读取新文件
        File writeFile = new File(uploadPath + fileName + "baccessory");
        log.info("写入文件路径:{}",writeFile);
        log.info("读取新文件:{}",writeFile.getName());
​
        //写入指定文件夹
        OutputStream out = new FileOutputStream(writeFile);
        out.write(bytes);
​
        return true;
    }
}
​

日期工具


import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * 时间常用工具类 如果 方法有变化 可以添加 自己需要的方法
 */
public class DateUtil {

    /*******  年-月-日  ******/
    public static final String YMD1 = "yyyy-MM-dd";
    /*******  年/月/日  ******/
    public static final String YMD2 = "yyyy/MM/dd";
    /*******  年-月-日 时:分:秒 ******/
    public static final String YMD3 = "yyyy-MM-dd HH:mm:ss";
    /*******  年月日时分秒 ******/
    public static final String YMD4 = "yyyyMMddHHmmss";
    /*******  年月日 ******/
    public static final String YMD5 = "yyyyMMdd";

    public static final String YMD6 = "yyyy-MM-dd HH:mm";

    public static final String YMD7 = "yyyy/MM/dd HH:mm:ss";

    public static final String YMD8 = "MM-dd";

    public static final String YMD9 = "yyyy.MM.dd";

    public static final String YMD10 = "yyyy-MM-dd HH:mm:ss.S";

    public static final String YMD11 = "HHmmss";

    /**
     * 时间转换成str
     *
     * @param date
     * @param format
     * @return
     */
    public static String dateToStr(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String dateStr = sdf.format(date);
        return dateStr;
    }


    /**
     * 时间Str 转换成 Date
     *
     * @param dateStr
     * @param format  当前的时间格式
     * @return
     */
    public static Date strToDate(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            System.out.printf("时间转换异常 -- dateStr " + dateStr);
            e.printStackTrace();
            date = new Date();
        }
        return date;
    }

    /**
     * 日期时间点  加上天数后的日期时间点
     *
     * @param num 为增加的天数
     * @return
     */
    public static Date timePlusDay(Date date, int num) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//设置时间
        cal.add(Calendar.DATE, num);// num为增加的天数,可以改变的
        return cal.getTime();
    }

    /**
     * 日期加上天数后的日期到日
     *
     * @param num 为增加的天数   此处支持负数 -n 是减去多少天
     * @return
     */
    public static Date datePlusDay(Date date, int num) {
        Date resultDate = timePlusDay(date, num);
        Calendar cal = Calendar.getInstance();
        cal.setTime(resultDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }


    /**
     * 将日期转为对应类型
     * @param format
     * @param localDate
     * @return
     */
    public static String dateFormatType(String format, LocalDate localDate){
        if (StringUtils.isBlank(format)) {
            format = YMD1;
        }

        if (null == localDate) {
            return null;
        }
        return localDate.format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * 时间区间校验
     *
     * @param stateTime
     * @param endTime
     * @return
     */
    public static String intervalCheck(LocalDateTime stateTime,LocalDateTime endTime,LocalDateTime newTime){

        //当前时间在开始时间之前 或者 当前时间在结束时间之后,都算不在区间内
        if (newTime.isBefore(stateTime) || newTime.isAfter(endTime)) {
            return "0";
        }
        return "1";
    }

    /**
     * 校验参数中时间 是否已过 当前系统时间
     * @param time
     * @return
     */
    public static boolean intervalCheck(LocalDateTime time) {
        return  LocalDateTime.now().isAfter(time);
    }

    /**
     * 任意数据时间格式转换
     *
     * @param date 时间数据
     * @param returnPattern 想要的返回格式
     */
    public static String allDateFormat(String date,String returnPattern){
        if (StringUtils.isBlank(date) || StringUtils.isBlank(returnPattern)) {
            return "";
        }

        //自动区分时间格式
        String pattern = "";
        if (10 == date.length() && date.contains("-")) {
            pattern = YMD1;

        }else if (10 == date.length() && date.contains("/")) {
            pattern = YMD2;

        }else if (19 == date.length() && date.contains("-")) {
            pattern = YMD3;

        }else if (14 == date.length()) {
            pattern = YMD4;

        }else if (8 == date.length()) {
            pattern = YMD5;

        }else if (16 == date.length()) {
            pattern = YMD6;

        }else if (19 == date.length() && date.contains("/")) {
            pattern = YMD7;

        }else if (5 == date.length()) {
            pattern = YMD8;

        }else if (10 == date.length() && date.contains(".")) {
            pattern = YMD9;

        }else if (21 == date.length()) {
            pattern = YMD10;

        }else{
            return "";
        }

        //时间
        LocalDateTime localDateTime = null;
        //日期 不带 时分秒
        if (pattern.length() <= 10) {
            localDateTime = LocalDateTime.of(LocalDate.parse(date,DateTimeFormatter.ofPattern(pattern)), LocalTime.MIN);
        }else{
            localDateTime = LocalDateTime.parse(date,DateTimeFormatter.ofPattern(pattern));
        }

        //转换成 想要的格式
        return localDateTime.format(DateTimeFormatter.ofPattern(returnPattern));
    }


    public static void main(String args[]) {
        System.out.println(allDateFormat("2019/07/23 12:34:12",YMD8));;
        System.out.println(allDateFormat("",YMD8));;
        System.out.println(allDateFormat("2019/07/23",YMD8));;
        System.out.println(allDateFormat("2019-07-23",YMD8));;
        System.out.println(allDateFormat("2019-07-23",YMD4));;
        System.out.println(allDateFormat("2019-07-23",YMD5));;
        System.out.println(allDateFormat("2019-07-23 12:35:35",YMD3));;
        System.out.println(allDateFormat("2019-07-23 12:35:35",YMD8));;
        System.out.println(allDateFormat("2019-07-23 12:35:35",YMD10));;
    }
}

脱敏


import org.apache.commons.lang3.StringUtils;

/**
 * 类名称: DisplayUtil <br>
 * 类描述: 敏感信息掩码规则<br>
 */
public class DisplayUtil {
	private DisplayUtil() {
	    throw new IllegalStateException("Utility class");
	}

    /**
     * 手机号显示首3末4位,中间用*号隐藏代替,如:138****4213
     *
     * @param mobile
     * @return
     */
    public static String displayMobile(String mobile) {
        if(StringUtils.isBlank(mobile) || mobile.length() <= 8) {
            return mobile;
        }

        return wordMask(mobile, 3, 4, "*");
    }

    /**
     * 电话号码显示区号及末4位,中间用*号隐藏代替,如:010****4213
     *
     * @param telephone
     * @return
     */
    public static String displayTelephone(String telephone) {
        if(StringUtils.isBlank(telephone)) {
            return telephone;
        }
        String result;
        if (telephone.length() > 8) {
            if (telephone.contains("-")) {
                String[] temp = telephone.split("-");
                result = temp[0] + "****" + temp[1].substring(temp[1].length() - 4, temp[1].length());
            } else {
                result = telephone.substring(0, 3) + "****" + telephone.substring(telephone.length() - 4, telephone.length());
            }
        } else {
            result = "****" + telephone.substring(telephone.length() - 4, telephone.length());
        }

        return result;
    }

    /**
     * 身份证号显示首3末3位,中间用*号隐藏代替,如:421*******012
     *
     * @param idCard
     * @return
     */
    public static String displayIDCard(String idCard) {
        if(StringUtils.isBlank(idCard)) {
            return idCard;
        }

        return wordMask(idCard, 3, 3, "*");
    }

    /**
     * 银行卡显示首3末3位,中间用*号隐藏代替,如:622********123
     *
     * @param cardNo
     * @return
     */
    public static String displayBankCard(String cardNo) {
        if(StringUtils.isBlank(cardNo) || cardNo.length() < 10) {
            return cardNo;
        }

        return wordMask(cardNo, 3, 3, "*");
    }

    /**
     * 邮箱像是前两位及最后一位字符,及@后邮箱域名信息,如:ye****y@163.com
     *
     * @param email
     * @return
     */
    public static String displayEmail(String email) {
        if(StringUtils.isBlank(email)) {
            return email;
        }
        String[] temp = email.split("@");

        return wordMask(temp[0], 1, 1, "*") + "@" + temp[1];
    }

    /**
     * 三个字掩码,如:张晓明 如:**明
     * 两个字掩码,如:小明 如:*明
     * 多个字掩码,如:张小明明 如:***明
     *
     * @param name
     * @return
     */
    public static String displayName(String name) {
        if(StringUtils.isBlank(name) || name.length() == 1) {
            return name;
        }
        if (name.length() == 2) {
            return "*" + name.substring(1, 2);
        }

        return wordMask(name, 0, 1, "*");
    }

    /**
     * 手机号脱敏:格式****1596
     * @param phone
     * @return
     */
    public static String displayPhone(String phone) {
        return "****" + phone.substring(phone.length()-4);
    }


    /**
     * Cvv全隐藏,如: ***
     *
     * @param cvv
     * @return
     */
    public static String displayCvv(String cvv) {
        if(StringUtils.isBlank(cvv)) {
            return cvv;
        }
        return "***";
    }

    /**
     * Expdate全隐藏,如: ****
     *
     * @param expdate
     * @return
     */
    public static String displayExpdate(String expdate) {
        if(StringUtils.isBlank(expdate)) {
            return expdate;
        }
        return "****";
    }

    /**
     * 对字符串进行脱敏处理 --
     *
     * @param word 被脱敏的字符
     * @param startLength 被保留的开始长度 前余n位
     * @param endLength 被保留的结束长度 后余n位
     * @param pad 填充字符
     * */
    public static String wordMask(String word,int startLength ,int endLength,String pad)    {

        if (startLength + endLength > word.length()) {
            return StringUtils.leftPad("", word.length() - 1, pad);
        }

        String startStr = word.substring(0, startLength);

        String endStr = word.substring(word.length() - endLength, word.length());

        return startStr + StringUtils.leftPad("", word.length() - startLength - endLength, pad) + endStr;

    }
}

分页

        //按照排序字段 倒序 排序
        String orderBy = "advice_id  DESC";

        Page page = PageHelper.startPage( pageNum, pageSize, orderBy);
		mapper.();//mapper 的方法

poi批量导入工具类

pom.xml

   <!-- easy poi的支持 -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.util.Date;

@Data
public class UploadDiscountDTO {
    @Excel(name = "产品内部代码")
    private String fundCode;

    @Excel(name = "产品名称")
    private String fundName;

    @Excel(name = "身份证号")
    private String identityNo;

    @Excel(name = "客户姓名")
    private String userName;

    @Excel(name = "开放日", importFormat = "yyyy-MM-dd")
    private Date openDay;

    @Excel(name = "开放日开始时间", importFormat = "yyyy-MM-dd HH:mm:ss")
    private Date startTime;

    @Excel(name = "开放日结束时间", importFormat = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;

    @Excel(name = "折扣率")
    private Double discountRate;

}

java

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.xinhu.wealth.manage.constant.Result;
import com.xinhu.wealth.manage.constant.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelEasyPOIUtil {
    /**
     * @description 导入Excel获取List<T>
     * @param multipartFile
     * @param t      DTO类
     * @return
     **/
    public static <T> Result getDTOListByExcel(MultipartFile multipartFile, T t){
        Result result = checkExcelFile(multipartFile);
        if(result.getCode()==200){
            List<T> uploadDTOList = new ArrayList<>();
            try {
                //从excel中读取数据
                ImportParams importParams = new ImportParams();
                importParams.setHeadRows(1);
                uploadDTOList = ExcelImportUtil.importExcel(multipartFile.getInputStream(), t.getClass(), importParams);

                log.info("上传的Excel列表uploadDTOList: {}", JSONObject.toJSONString(uploadDTOList));
                return Result.success(uploadDTOList);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }

        }else {
            return result;
        }

    }

    /**
     * @description 检查Excel文件
     * @param multipartFile
     * @return
     **/
    public  static Result checkExcelFile(MultipartFile multipartFile){
        if (null == multipartFile || multipartFile.getSize() <= 0) {
            return Result.genResult(ResultEntity.VALIDATION_FAILED.getCode(),"请选择上传的Excel文件!");
        }
        //获得文件名
        String fileName = multipartFile.getOriginalFilename();
        //判断文件是否是excel文件
        if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
            return Result.genResult(ResultEntity.VALIDATION_FAILED.getCode(),"上传的不是Excel文件!");
        }
        return Result.success();
    }
}

easypoi的导出

依赖

        <!--easypoi-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>
@ExcelTarget("EContractEditRecordDTO")
public class EContractEditRecordDTO implements Serializable {

   private static final long serialVersionUID = 1L;
   /**
    * 合同编号
    */
   @Excel(name = "合同编号", width = 20, needMerge = true)
   private String fContractNo;

   /**
    * 电子合同类型  1 劳动合同  2 绩效合同
    */
   @Excel(name = "电子合同类型", width = 20, needMerge = true, replace = {"绩效合同_2", "劳务合同_1"})
   private int eContractType;

   /**
    * 员工编码
    */
   @Excel(name = "员工编码", width = 20, needMerge = true)
   private String fNumber;

   /**
    * 员工姓名
    */
   @Excel(name = "员工姓名", width = 20, needMerge = true)
   private String cFtrueName;

   //子条目集合(这里是实现一对多的关键。name=""是为了不出现表头,如果不为空表头会多一层合并的单元格)
   @ExcelCollection(name = "")
   private List<EditRecordList> recordLists;

   /**
    * 审核状态  3信息审核中 4信息已复核、5信息未通过复核'
    */
   @Excel(name = "审核状态", width = 20, needMerge = true, replace = {"信息审核中_3", "信息已复核_4","信息未通过复核_5"})
   private String auditStatus;

  //get/set
}
@ExcelTarget("EditRecordList")
public class EditRecordList implements Serializable {

   private static final long serialVersionUID = 1L;


   private Long id;

   /**
    * 修改人的id
    */
   @Excel(name = "修改人的工号",width = 30)
   private String updatorId;

   /**
    * 修改人的姓名
    */
   @Excel(name = "修改人的姓名",width = 30)
   private String updatorName;

   /**
    * 修改人的类型
    */
   @Excel(name = "修改人的类型",width = 30,replace = {"员工_1","人力_2"})
   private int updatorType;

   /**
    * 修改的字段key
    */
   @Excel(name = "修改的字段",width = 30)
   private String tableKey;

   /**
    * 修改的字段展示标题
    */
   @Excel(name = "修改的字段展示标题",width = 30)
   private String tableName;

   /**
    * 字段旧数据
    */
   @Excel(name = "字段旧数据",width = 30)
   private String tableValueOld;

   /**
    * 字段新数据
    */
   @Excel(name = "字段新数据",width = 30)
   private String tableValueNew;

   /**
    * 修改时间
    */
   @Excel(name = "修改时间",width = 30)
   private LocalDateTime updateTime;

   public static long getSerialVersionUID() {
      return serialVersionUID;
   }
}
   private String getExcel(List<EContractEditRecordDTO> mainList) throws Exception {
      log.info("开始进入导出excel方法");
      // 简单模板导出方法
      ExportParams params = new ExportParams();
      params.setSheetName("字段修改信息");//设置sheet名
      Workbook workbook = ExcelExportUtil.exportExcel(params, EContractEditRecordDTO.class, mainList);
      //返回头设置下载,并设置文件名,返回
      String rs = domainNamePath + new ExportExcel().setExportExcelFormat(workbook, filePath + "字段修改信息");
      log.info("导出成功,url={}", rs);
      return rs;
   }

md5加密

        String signstr = DigestUtils.md5DigestAsHex(("需要加密的字符串").getBytes());

自定义 注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CheckToken {
    /**
     * 校验token并根据该值决定是否将userId透传到controller的方法
     */
    boolean transmitUserId() default true;
}


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import xinhu.wealth.shr.annotation.Authentication;
import xinhu.wealth.shr.annotation.CheckToken;
import xinhu.wealth.shr.annotation.NotCheckToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import xinhu.wealth.shr.constants.ProjectConstant;
import xinhu.wealth.shr.constants.Result;
import xinhu.wealth.shr.constants.ResultEntity;
import xinhu.wealth.shr.core.util.MD5Util;
import xinhu.wealth.shr.core.util.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;


@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        Map<String, Claim> claimMap;//生成token时的自定义值
        log.info("@@@@全局拦截器-requestURI={},token={}", requestURI, token);

        //如果是第三方调用接口 先校验是否有权限  没有权限直接返回  有权限继续往下走
        if (method.isAnnotationPresent(Authentication.class)) {
            String sign = request.getHeader("sign");
            String appId = request.getHeader("appId");
            String timestamp = request.getHeader("timestamp");
            log.info("@@@@外部调用入参sign={},appId={},timestamp={}", sign, appId, timestamp);
            Boolean flag = MD5Util.verifySign(sign, appId, timestamp);
            log.info("@@@@外部调用身份验证结果={}", flag);
            if (!flag) {
                returnJson(response, JSON.toJSONString(Result.success(ResultEntity.SIGNATURE_ERROR)));
                return false;
            }
        }

        if (method.isAnnotationPresent(CheckToken.class)) {//有CheckToken注解,需要校验token
            try {
                claimMap = TokenUtils.verifyToken(token);
                //token校验成功-->是否传递userId
                CheckToken checkToken = method.getAnnotation(CheckToken.class);
                if (checkToken.transmitUserId()) {
                    String userId = TokenUtils.getAppUID(claimMap);
                    request.setAttribute(ProjectConstant.USER_ID, userId);
                }
            } catch (Exception e) {
                log.error("@@@@全局拦截器-token校验异常", e);
                returnJson(response, JSON.toJSONString(Result.failure().setMessage("token错误")));
                return false;
            }
        } else if (method.isAnnotationPresent(NotCheckToken.class)) {//不校验token,有token时也可以透传userId
            NotCheckToken notCheckToken = method.getAnnotation(NotCheckToken.class);
            if (!StringUtils.isEmpty(token) && notCheckToken.transmitUserId()) {
                try {
                    claimMap = TokenUtils.verifyToken(token);
                    String userId = TokenUtils.getAppUID(claimMap);
                    request.setAttribute(ProjectConstant.USER_ID, userId);
                } catch (Exception e) {
                    log.warn("@@@@全局拦截器-接口不校验token但解析失败", e);
                }
            }
        }
        return true;
    }

    /**
     * 返回客户端数据
     *
     * @param response
     * @param json
     * @throws Exception
     */
    private void returnJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            log.error("返回客户端数据异常");
        }
    }
}

\