Spring boot 动态修改controller请求参数

需求:很多接口需要分页,前端传过来为createTime, 但后端需要create_time 才能查询记录,在每个接口改工作量大,所以放切面统一驼峰改下划线.

相关工作只需要写一个类,即可处理所有controller类参数有page的接口

package ;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.mgt.util.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 切面修改分页请求参数
 */
@Aspect
@Component
public class ParamAspect {

    /**
     * 前置通知
     */
    @Before("execution(* com.xxx.xxx.controller.*.*(com.baomidou.mybatisplus.extension.plugins.pagination.Page, *))")
    public void proceed(JoinPoint joinPoint) throws Throwable {
        Object[] obj = joinPoint.getArgs();
        for (Object obj1 : obj) {
            if (obj1 instanceof Page) {
                Page page = (Page)obj1;
                if (page.descs() != null) {
                    page.setDesc(StringUtil.humpToLine(page.descs()));
                }
                if (page.ascs() != null) {
                    page.setAsc(StringUtil.humpToLine(page.ascs()));
                }
                break;
            }
        }
    }
}


public class StringUtil {

    public static final char UNDERLINE = '_';

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 字符串:驼峰转下划线
     * @param param
     * @return
     */
    public static String humpToLine(String param){
        Matcher matcher = humpPattern.matcher(param);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()){
            matcher.appendReplacement(sb, UNDERLINE + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 数组:驼峰转下划线
     * @param param
     * @return
     */
    public static String[] humpToLine(String... param) {
        for (int i = 0; i<param.length; i++) {
            param[i] = humpToLine(param[i]);
        }
        return param;
    }
}

 


版权声明:本文为u011385940原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。