1.aop参数拦截
代码如下(示例):
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Mr.ch
* @description: aop日志
* @date 2021/7/26 16:58
*/
@Slf4j
@Aspect
@Component
public class LogAopAction {
/**
* 请求开始时间
*/
private long beginTime;
/**
* 请求结束时间
*/
private long endTime;
@Pointcut("execution(* com.csdn.xxx.controller.*.*(..))")
private void controllerAspect() {
}
/**
* 方法开始执行
*/
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) throws IllegalAccessException {
beginTime = System.currentTimeMillis();
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String method = request.getMethod();
Map<String, String> map = new HashMap<>(16);
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String name = parameterNames.nextElement();
map.put(name, request.getParameter(name));
}
Object[] args = joinPoint.getArgs();
String bodyParams = "";
//获取请求参数集合并进行遍历拼接
if (args.length > 0) {
if ("POST".equals(method)) {
Object object = args[0];
Map<String, Object> bodyMap = getKeyAndValue(object);
bodyParams = JSON.toJSONString(bodyMap);
}
}
log.info("请求IP: {}", RequestUtil.getRemoteHost(request));
log.info("请求路径: {}", request.getRequestURI());
log.info("请求方式: {}", method);
log.info("params参数: {}", JSON.toJSONString(map));
log.info("body参数: {}", bodyParams);
}
/**
* 方法结束执行
*/
@After("controllerAspect()")
public void after() {
endTime = System.currentTimeMillis();
}
/**
* 方法结束执行后的操作
*/
@AfterReturning(value = "controllerAspect()", returning = "returnObj")
public void doAfter(Object returnObj) {
String returnObjJson = JSONObject.toJSONString(returnObj);
log.info("执行耗时时间:{}ms, 返回的参数信息:{}", endTime - beginTime, returnObjJson);
}
/**
* 方法有异常时的操作
*/
@AfterThrowing(value = "controllerAspect()", throwing = "throwing")
public void doAfterThrow(BaseException throwing) {
log.error("切面捕获到异常信息 :" + throwing.getMessage());
}
/**
* 方法执行
*/
@Around("controllerAspect()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
return proceedingJoinPoint.proceed();
}
public static Map<String, Object> getKeyAndValue(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>(16);
// 得到类对象
Class<?> userCla = obj.getClass();
//得到类中的所有属性集合
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
// 设置些属性是可以访问的
f.setAccessible(true);
Object val = f.get(obj);
// 得到此属性的值 设置键值
map.put(f.getName(), val);
}
return map;
}
}
2.RequestUtil
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* Created by @author Mr.ch on 2021/7/26 16:58.
*/
public class RequestUtil {
public static final String UNKNOWN = "unknown";
/**
* 查找当前请求参数的ip地址
*
* @param request request请求对象
* @return 当前请求的ip
*/
public static String getRemoteHost(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (isNotRealIp(ip)) {
if (isNotRealIp(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (isNotRealIp(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (isNotRealIp(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (isNotRealIp(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (isNotRealIp(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
ip = Arrays.stream(ips)
.filter(strIp -> !(UNKNOWN.equalsIgnoreCase(strIp)))
.findFirst()
.orElse(ip);
}
return ip;
}
private static boolean isNotRealIp(String ip) {
return ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip);
}
}
3.公共异常类
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 公共异常
* Created by @author Mr.ch on 2021/7/26 16:58.
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class BaseException extends RuntimeException{
private static final long serialVersionUID = -3605030911925262261L;
private String msg;
private String code;
public BaseException(String code) {
super(code);
initBaseException(code, ReturnCodeType.getNameByCode(code));
}
public BaseException(String code, String message) {
super(code);
initBaseException(code,message);
}
public BaseException(String code,String message, Throwable cause ) {
super(code, cause);
initBaseException(code,message);
}
public BaseException(String code,Throwable cause) {
super(code,cause);
this.code = code;
}
public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String code) {
super(message, cause, enableSuppression, writableStackTrace);
initBaseException(code,message);
}
public BaseException(ReturnCodeType returnCodeType){
super(returnCodeType.getCode());
initBaseException(returnCodeType.getCode(),returnCodeType.getName());
}
public BaseException(ReturnCodeType returnCodeType, Throwable cause){
super(cause);
initBaseException(returnCodeType.getCode(),returnCodeType.getName());
}
private void initBaseException(String code, String message){
this.msg = message;
this.code = code;
}
}
4.错误枚举类
import lombok.Getter;
import java.util.Arrays;
/**
* 返回 错误码类型
* Created by @author Mr.ch on 2021/7/26 16:58.
*/
public enum ReturnCodeType {
BASE_SUCCESS("0", "操作成功!"),
BASE_ERROR("-1", "操作失败!"),
;
/**
* 错误码
*/
@Getter
private String code;
/**
* 错误提示
*/
@Getter
private String name;
ReturnCodeType(String code, String name) {
this.code = code;
this.name = name;
}
public static String getNameByCode(String code) {
return Arrays.stream(ReturnCodeType.values())
.filter(codeType -> codeType.getCode().equals(code))
.findFirst()
.map(ReturnCodeType::getName)
.orElse(ReturnCodeType.getNameByCode(code));
}
public static boolean inCode(String code) {
return Arrays.stream(ReturnCodeType.values()).map(ReturnCodeType::getCode).anyMatch(code::equals);
}
}