Spring切面处理日志

业务场景:在web服务中添加日志,要求在刚进入方法和结束方法的时候打印开始和结束日志;进入方法好说,直接在第一行打印即可,但是return的时候可能会有很多分支,所以我们必须要在更上一层进行处理

实现步骤:
1.创建TestRequestBodyAdvice并实现RequestBodyAdvice接口,类上添加注解@ControllerAdvice
2.创建TestResponseBodyAdvice并实现ResponseBodyAdvice接口,类上添加注解@ControllerAdvice
3.修改其中的默认返回值;例如null改为对应值,false改为true(这个不要盲目的改)
4.引入logger类
5.在关键位置写入要打印的日志
具体代码如下:

@ControllerAdvice
public class TestRequestBodyAdvice implements RequestBodyAdvice {

    private Logger logger= LoggerFactory.getLogger(TestRequestBodyAdvice.class);

    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    public Object afterBodyRead(Object object, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        logger.debug("即将进入{}方法",methodParameter.getMethod().getName());
        return object;
    }

    public Object handleEmptyBody(Object object, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return object;
    }
}




@ControllerAdvice
public class TestResponseBodyAdvice implements ResponseBodyAdvice {

    private Logger logger= LoggerFactory.getLogger(TestResponseBodyAdvice.class);

    public boolean supports(MethodParameter methodParameter, Class aClass) {
        if (aClass.isAssignableFrom(MappingJackson2CborHttpMessageConverter.class)){
            return true;
        }
        return false;
    }

    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        logger.debug("即将进入{}方法",methodParameter.getMethod().getName());
        return object;
    }
}
* 以上两个类并非只是打印日志的作用,他可以在所有请求的进入和返回时刻进行处理,例如进行简单的参数校验,或者查询为空时在此处理给前端一个默认返回值等

* 以上代码采用了适配器模式,通过supports函数来判断是否进入下面的函数进行逻辑处理

Spring实现数据字典翻译

在开始之前,首先我们要了解一个类:BeanPropertyWriter。
这个类是由SerializerFactory 工厂进行实例化的,其作用是对bean中的每个字段进行jackson操作的封装,其中封装了字段的一些元信息,和对此字段进行jackson序列化的操作。
采用Spring项目进行Web服务开发时,在获取到数据后,Spring会通过BeanPropertyWriter对数据进行jackson封装,将其转换为Json串。
如果我们需要在不影响逻辑的情况下对数据进行字典翻译,重写此类是较好的选择

字典翻译实现步骤:
1.实现获取字典的接口 read more

Java实现Excel读取

背景:
每个月公司都会有发两个表,
一个是考勤表
另一个是工时表
需要我们对照考勤表把工时表完善
写了两次实在是感觉很浪费时间,于是就写了个代码代替人工
pom引用

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version>
</dependency>
package com.justin.excel;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 * 读写Excel
 *
 * @author Justin.Sun
 * @create 2018-07-30 17:34
 */
public class ExcelUtil {
    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";
    private static Map<Integer,Integer> time=new HashMap<Integer, Integer>();
    private static Map<Integer,String> data=new HashMap<Integer, String>();
    private static FileInputStream in;
    private static Workbook workBook = null;
    private static  FileOutputStream out;

    /**
     * 读取考勤表并获取userName相关数据
     * @param fileName 文件路径
     * @param userName 名字
     * @throws IOException
     */
    public static void readExcel(String fileName,String userName) throws IOException {
        Sheet sheet=getSheet(fileName);
        // 第一行从0开始算
        int rowNumber = sheet.getLastRowNum();
        //逐行循环
        for (int i = 1; i <= rowNumber; i++) {
            Row row = sheet.getRow(i);
            if (row==null){
                System.out.println("获取到的行数"+i);
                break;
            }
            Cell cell;
            boolean arg=false;
            //循环行内的列
            for (int j=0;j<=row.getLastCellNum();j++){
                cell=row.getCell(j);
                if (cell==null){
                    break;
                }
                //获取数据的规则
                if (i==2){
                    String value=cell.toString();
                    try{
                        int day=Integer.parseInt(value);
                        time.put(day,j);
                    }catch (Exception e){
                        continue;
                    }
                }else if (i>2&&j==0&&userName.equals(cell.toString())){
                    arg=true;
                    for (int key:time.keySet()){
                        cell=row.getCell(time.get(key));
                        data.put(key,cell.toString().replace("\n","&").replaceAll("  ",""));
                    }
                }
            }
            //得到了我想要的数据,可以结束循环了
            if (arg){
                System.out.println(data);
                System.out.println("获取 "+userName+" 数据完成");
                break;
            }
        }
        close();
    }

    /**
     * 写入数据到工时表
     * @param fileName 文件路径
     * @param userName 名字
     * @throws IOException
     */
    public static void writeExcel(String fileName,String userName) throws IOException {
        SimpleDateFormat sdf=new SimpleDateFormat("d");
        Sheet sheet=getSheet(fileName);
        int rowNumber = sheet.getLastRowNum();
        for (int i = 1; i <= rowNumber; i++) {
            Row row = sheet.getRow(i);
            if (row==null){
                System.out.println("获取到的行数"+i);
                break;
            }
            Cell cell;
            //行循环
            for (int j=0;j<=row.getLastCellNum();j++){
                cell=row.getCell(j);
                if (cell==null){
                    break;
                }
                //名字替换
                if ("某某".equals(cell.toString())){
                    cell.setCellValue(userName);
                }
                //数据处理
                if (i>3&&j==1){
                    try{
                        int day= Integer.parseInt(sdf.format(cell.getDateCellValue()));
                        String value=data.get(day);
                        int index=value.indexOf("&");
                        String startTime="";
                        String endTime="";
                        if (index>0){
                            startTime=value.substring(0,index);
                            endTime=value.substring(index+1,value.length());
                        }
                        cell=row.getCell(3);
                        cell.setCellValue(startTime);
                        cell=row.getCell(4);
                        cell.setCellValue(endTime);
                        if (startTime.equals("")&&endTime.equals("")){
                            cell=row.getCell(5);
                            cell.setCellValue("");
                        }
                    }catch (Exception e){
                        cell=row.getCell(5);
                        //找到引用函数的单元格
                        if (cell.getCellType()==Cell.CELL_TYPE_FORMULA){
                            //执行函数并得到返回值
                            FormulaEvaluator evaluator = workBook.getCreationHelper().createFormulaEvaluator();
                            CellValue cellValue=evaluator.evaluate(cell);
                            //替换新值到单元格
                            cell.setCellValue(cellValue.getNumberValue());
                        }
                    }
                }
            }
        }
        out=new FileOutputStream(fileName);
        workBook.write(out);
        close();
        System.out.println("写入 "+userName+" 数据完成");
    }

    /**
     * 创建连接并获取工作薄
     * @param fileName 文件路径
     * @return 工作薄对象
     * @throws IOException
     */
    private static Sheet getSheet(String fileName) throws IOException {
        File file=new File(fileName);
        in = new FileInputStream(file);
        //Excel&nbsp;2003
        if(file.getName().endsWith(EXCEL_XLS)){
            workBook = new HSSFWorkbook(in);
            // Excel 2007/2010
        }else if(file.getName().endsWith(EXCEL_XLSX)){
            workBook = new XSSFWorkbook(in);
        }
        //默认获取第一个工作薄
        return workBook.getSheetAt(0);
    }

    /**
     * 关闭连接
     * @throws IOException
     */
    private static void close() throws IOException {
        if (workBook!=null){
            workBook.close();
        }
        if (in!=null){
            in.close();
        }
        if (out!=null){
            out.close();
        }
    }
}

public class Application {
    private static String readFileName="E:/考勤表.xlsx";
    private static String writeFileName="E:/空白工时表.xlsx";
    private static String userName="Justin";
    public static void main(String[] args) throws IOException {
        //执行
        ExcelUtil.readExcel( readFileName,userName);
        ExcelUtil.writeExcel( writeFileName,userName);
    }
}

Java实现字段脱敏处理

     /**
     * [中文姓名] 只显示第一个汉字,其他隐藏为2个星号<例子:李**>
     *
     * @param fullName
     * @return
     */
    public static String chineseName(String fullName) {
        if (StringUtils.isBlank(fullName)) {
            return "";
        }
        String name = StringUtils.left(fullName, 1);
        return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
    }

    /**
     * [中文姓名] 只显示第一个汉字,其他隐藏为2个星号<例子:李**>
     *
     * @param familyName
     * @param givenName
     * @return
     */
    public static String chineseName(String familyName, String givenName) {
        if (StringUtils.isBlank(familyName) || StringUtils.isBlank(givenName)) {
            return "";
        }
        return chineseName(familyName + givenName);
    }

    /**
     * [身份证号] 显示最后四位,其他隐藏。共计18位或者15位。<例子:*************5762>
     *
     * @param id
     * @return
     */
    public static String idCardNum(String id) {
        if (StringUtils.isBlank(id)) {
            return "";
        }
        String num = StringUtils.right(id, 4);
        return StringUtils.leftPad(num, StringUtils.length(id), "*");
    }

    /**
     * [固定电话] 后四位,其他隐藏<例子:****1234>
     *
     * @param num
     * @return
     */
    public static String fixedPhone(String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*");
    }

    /**
     * [手机号码] 前三位,后四位,其他隐藏<例子:138******1234>
     *
     * @param num
     * @return
     */
    public static String mobilePhone(String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.left(num, 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*"), "***"));
    }

    /**
     * [地址] 只显示到地区,不显示详细地址;我们要对个人信息增强保护<例子:北京市海淀区****>
     *
     * @param address
     * @param sensitiveSize
     *            敏感信息长度
     * @return
     */
    public static String address(String address, int sensitiveSize) {
        if (StringUtils.isBlank(address)) {
            return "";
        }
        int length = StringUtils.length(address);
        return StringUtils.rightPad(StringUtils.left(address, length - sensitiveSize), length, "*");
    }

    /**
     * [电子邮箱] 邮箱前缀仅显示第一个字母,前缀其他隐藏,用星号代替,@及后面的地址显示<例子:g**@163.com>
     *
     * @param email
     * @return
     */
    public static String email(String email) {
        if (StringUtils.isBlank(email)) {
            return "";
        }
        int index = StringUtils.indexOf(email, "@");
        if (index <= 1) {
            return email;
        }else{
            return StringUtils.rightPad(StringUtils.left(email, 1), index, "*").concat(StringUtils.mid(email, index, StringUtils.length(email)));
        }
    }

    /**
     * [银行卡号] 前六位,后四位,其他用星号隐藏每位1个星号<例子:6222600**********1234>
     *
     * @param cardNum
     * @return
     */
    public static String bankCard(String cardNum) {
        if (StringUtils.isBlank(cardNum)) {
            return "";
        }
        return StringUtils.left(cardNum, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(cardNum, 4), StringUtils.length(cardNum), "*"), "******"));
    }

    /**
     * [公司开户银行联号] 公司开户银行联行号,显示前两位,其他用星号隐藏,每位1个星号<例子:12********>
     *
     * @param code
     * @return
     */
    public static String cnapsCode(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        return StringUtils.rightPad(StringUtils.left(code, 2), StringUtils.length(code), "*");
    }

使用git命令上传项目到远程仓库

右键打开git Bash Here

1.cd到项目所在目录,例如
cd C:\workspace\zjwk\finger-search

2.在当前目录下初始化git仓库
git init

3.关联远程仓库
git remote add origin <你的项目地址> 
//注:项目地址形式为:http://git.oschina.net/xxx/xxx.git或者

4.提交到暂存区
git add .

5.提交到本地仓库
git commit -m "first"

6.推送到远程仓库
git push origin master

7.如果你再远程仓库设置项目为私有化
那么此处则需要输入账号密码
(我再输入账号密码的时候始终无法通过验证)
于是就转用ssh提交

8.检查连接
$ git remote -v
可看到
origin  https://gitee.com/nyjcq/yilianjiaoyu.git (fetch)
origin  https://gitee.com/nyjcq/yilianjiaoyu.git (push)
我们可以看出当前是https连接

9.移除当前连接
git remote remove origin

10.建立新的连接
git remote add origin  git@gitee.com:nyjcq/yilianjiaoyu.git;
此时检查连接可发现https已经变成git方式

11.此时推送到远程仓库
$ git push -u origin master
如推送成功则结束
如不成功则需对密钥进行重新设置

12.删除当前key,然后重新生成key
$ ssh-keygen -t rsa -C "964936066@qq.com"

会在本地C:\Users\你的用户名.ssh生成文件夹,
里面有id_rsa和id_rsa.pub两个文件 
然后复制id_rsa.pub文件里面的内容,
到码云SSH公钥设置重新创建一个即可

13.通过查看可发现原来的远程连接已经没有了,需重新建立连接
git remote add origin  git@gitee.com:nyjcq/yilianjiaoyu.git;

14.执行提交上传
$ git push -u origin master
以上部分为首次上传情况
以下将主要针对二次上传出现的情况
1.提交到暂存区
git add .

2.提交到本地仓库
git commit -m "first"

3.推送到远程仓库
git push origin master
如遇冲突,可执行

强制推送(舍弃线上)
git push origin master -f

下拉覆盖(保留线上)
git pull origin master
此时如果无法进行自动合并,则需手动合并
如下图
http://git.oschina.net/uploads/images/2016/0226/114058_429e8b54_62561.gif

码云官方文档-如何解决冲突