package com.ruoyi.common.security.aspect;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.common.core.annotation.DictStr;
import com.ruoyi.system.api.domain.SysDictData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Aspect
@Component
public class DictAspect {
@Pointcut("execution(public * com.ruoyi.*.controller..*.*(..))")
public void webLog() {
}
@Around("webLog()")
public Object afterMethod(ProceedingJoinPoint point) throws Throwable {
Object proceed = point.proceed();
if (proceed instanceof TableDataInfo) {
Class<?> aClass = proceed.getClass();
Field field = aClass.getDeclaredField("rows");
field.setAccessible(true);
if (field.getName().equals("rows")) {
List<?> rows = (List<?>) field.get(proceed);
list(rows);
}
}
if (proceed instanceof R) {
Object data = ((R<?>) proceed).getData();
if (data instanceof List) {
List<?> rows = (List<?>) data;
list(rows);
} else if (data instanceof IPage) {
IPage<?> page = (IPage<?>) data;
List<?> rows = page.getRecords();
list(rows);
} else {
row(data);
}
}
return proceed;
}
private void list(List<?> rows) throws Exception {
for (Object obj : rows) {
row(obj);
}
}
private void row(Object obj) throws Exception {
Class<?> aClass = obj.getClass();
Map<String, Object> map = new HashMap<>();
for (Field field : aClass.getDeclaredFields()) {
field.setAccessible(true);
DictStr annotation = field.getAnnotation(DictStr.class);
if (annotation != null) {
Object value = field.get(obj);
List<SysDictData> sysDictData = DictUtils.getDictCache(annotation.dictType());
if (sysDictData == null) {
map.put(field.getName() + "Str", "未知");
return;
}
Optional<SysDictData> optional = sysDictData.stream().filter(f -> f.getDictValue().equals(String.valueOf(value))).findFirst();
if (optional.isPresent()) {
map.put(field.getName() + "Str", optional.get().getDictLabel());
} else {
map.put(field.getName() + "Str", "未知");
}
}
}
try {
Class<?> superclass = aClass.getSuperclass();
Field field = superclass.getDeclaredField("dictMap");
field.setAccessible(true);
field.set(obj, map);
} catch (NoSuchFieldException ignored) {
}
}
}
package com.ruoyi.common.core.annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Target({FIELD, METHOD, PARAMETER, TYPE, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface DictStr {
String dictType() default "";
}
