update 优化 项目中的一些存在null的问题 与一些性能问题 小优化

This commit is contained in:
疯狂的狮子Li
2026-03-31 18:52:37 +08:00
parent 26464c0051
commit d11990bfd8
21 changed files with 137 additions and 91 deletions

View File

@@ -23,6 +23,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
public static final String SLASH = "/";
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
@Deprecated
private StringUtils() {
}
@@ -233,8 +235,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* @param url 需要匹配的url
*/
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
return ANT_PATH_MATCHER.match(pattern, url);
}
/**

View File

@@ -1,5 +1,6 @@
package org.dromara.common.core.utils.sql;
import cn.hutool.core.exceptions.UtilException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
@@ -15,7 +16,7 @@ public class SqlUtil {
/**
* 定义常用的 sql关键字
*/
public static String SQL_REGEX = "\u000B|and |extractvalue|updatexml|sleep|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |union |like |+|/*|user()";
public static final String SQL_REGEX = "\u000B|%0A|and |extractvalue|updatexml|sleep|information_schema|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |union |like |+|/*|user()";
/**
* 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
@@ -46,10 +47,11 @@ public class SqlUtil {
if (StringUtils.isEmpty(value)) {
return;
}
String normalizedValue = value.replaceAll("\\p{Z}|\\s", "");
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
for (String sqlKeyword : sqlKeywords) {
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
throw new IllegalArgumentException("参数存在SQL注入风险");
if (StringUtils.indexOf(normalizedValue, sqlKeyword) > -1) {
throw new UtilException("请求参数包含敏感关键词'" + sqlKeyword + "',可能存在安全风险");
}
}
}

View File

@@ -38,6 +38,9 @@ public class ExcelBigNumberConvert implements Converter<Long> {
@Override
public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (ObjectUtil.isNull(object)) {
return new WriteCellData<>("");
}
if (ObjectUtil.isNotNull(object)) {
String str = Convert.toStr(object);
if (str.length() > 15) {

View File

@@ -16,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 枚举格式化转换处理
@@ -25,6 +26,9 @@ import java.util.Map;
@Slf4j
public class ExcelEnumConvert implements Converter<Object> {
private static final Map<Field, Map<Object, String>> ENUM_MAP_CACHE = new ConcurrentHashMap<>();
private static final Map<Field, Map<Object, Object>> ENUM_REVERSE_MAP_CACHE = new ConcurrentHashMap<>();
@Override
public Class<Object> supportJavaTypeKey() {
return Object.class;
@@ -50,10 +54,15 @@ public class ExcelEnumConvert implements Converter<Object> {
return null;
}
Map<Object, String> enumCodeToTextMap = beforeConvert(contentProperty);
// 从Java输出至Excel是code转text
// 因此从Excel转Java应该将text与code对调
Map<Object, Object> enumTextToCodeMap = new HashMap<>();
enumCodeToTextMap.forEach((key, value) -> enumTextToCodeMap.put(value, key));
// 从Java输出至Excel是code转text从Excel转Java应将text与code对调
Map<Object, Object> enumTextToCodeMap = ENUM_REVERSE_MAP_CACHE.computeIfAbsent(
contentProperty.getField(),
f -> {
Map<Object, Object> reverseMap = new HashMap<>();
enumCodeToTextMap.forEach((key, value) -> reverseMap.put(value, key));
return reverseMap;
}
);
// 应该从text -> code中查找
Object codeValue = enumTextToCodeMap.get(textValue);
return Convert.convert(contentProperty.getField().getType(), codeValue);
@@ -70,15 +79,17 @@ public class ExcelEnumConvert implements Converter<Object> {
}
private Map<Object, String> beforeConvert(ExcelContentProperty contentProperty) {
ExcelEnumFormat anno = getAnnotation(contentProperty.getField());
Map<Object, String> enumValueMap = new HashMap<>();
Enum<?>[] enumConstants = anno.enumClass().getEnumConstants();
for (Enum<?> enumConstant : enumConstants) {
Object codeValue = ReflectUtils.invokeGetter(enumConstant, anno.codeField());
String textValue = ReflectUtils.invokeGetter(enumConstant, anno.textField());
enumValueMap.put(codeValue, textValue);
}
return enumValueMap;
return ENUM_MAP_CACHE.computeIfAbsent(contentProperty.getField(), field -> {
ExcelEnumFormat anno = getAnnotation(field);
Map<Object, String> enumValueMap = new HashMap<>();
Enum<?>[] enumConstants = anno.enumClass().getEnumConstants();
for (Enum<?> enumConstant : enumConstants) {
Object codeValue = ReflectUtils.invokeGetter(enumConstant, anno.codeField());
String textValue = ReflectUtils.invokeGetter(enumConstant, anno.textField());
enumValueMap.put(codeValue, textValue);
}
return enumValueMap;
});
}
private ExcelEnumFormat getAnnotation(Field field) {

View File

@@ -73,6 +73,10 @@ public class DefaultExcelListener<T> extends AnalysisEventListener<T> implements
log.error(errMsg);
}
}
if (errMsg == null) {
errMsg = StrUtil.format("第{}行数据异常: {}", context.readRowHolder().getRowIndex() + 1, exception.getMessage());
log.error(errMsg, exception);
}
excelResult.getErrorList().add(errMsg);
throw new ExcelAnalysisException(errMsg);
}

View File

@@ -66,7 +66,7 @@ public class DefaultExcelResult<T> implements ExcelResult<T> {
if (errorCount == 0) {
return StrUtil.format("恭喜您,全部读取成功!共{}条", successCount);
} else {
return "";
return StrUtil.format("共{}条,成功导入{}条,错误{}条", successCount + errorCount, successCount, errorCount);
}
}
}

View File

@@ -182,9 +182,10 @@ public class ExcelDownHandler implements SheetWriteHandler {
Sheet linkedOptionsDataSheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(linkedOptionsSheetName));
// 将下拉表隐藏
workbook.setSheetHidden(workbook.getSheetIndex(linkedOptionsDataSheet), true);
// 选项数据
// 选项数据(使用副本,避免修改调用方的原始数据)
List<String> firstOptions = options.getOptions();
Map<String, List<String>> secoundOptionsMap = options.getNextOptions();
Map<String, List<String>> secoundOptionsMap = new HashMap<>();
options.getNextOptions().forEach((k, v) -> secoundOptionsMap.put(k, new ArrayList<>(v)));
// 采用按行填充数据的方式,避免出现数据无法写入的问题
// Attempting to write a row in the range that is already written to disk
@@ -378,7 +379,6 @@ public class ExcelDownHandler implements SheetWriteHandler {
//选定提示
dataValidation.createPromptBox("填写说明:", "填写内容只能为下拉中数据,其他数据将导致导入失败");
dataValidation.setShowPromptBox(true);
sheet.addValidationData(dataValidation);
} else {
dataValidation.setSuppressDropDownArrow(false);
}

View File

@@ -99,6 +99,9 @@ public class DataWriteHandler implements SheetWriteHandler, CellWriteHandler {
}
ExcelRequired excelRequired = field.getAnnotation(ExcelRequired.class);
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty == null || excelProperty.value().length == 0) {
continue;
}
requiredMap.put(excelProperty.value()[0], excelRequired.fontColor().getIndex());
}
return requiredMap;
@@ -116,6 +119,9 @@ public class DataWriteHandler implements SheetWriteHandler, CellWriteHandler {
}
ExcelNotation excelNotation = field.getAnnotation(ExcelNotation.class);
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty == null || excelProperty.value().length == 0) {
continue;
}
notationMap.put(excelProperty.value()[0], excelNotation.value());
}
return notationMap;

View File

@@ -89,7 +89,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportExcel(list, sheetName, clazz, false, os, null);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -108,7 +108,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportExcel(list, sheetName, clazz, false, os, options);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -127,7 +127,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportExcel(list, sheetName, clazz, merge, os, null);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -147,7 +147,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportExcel(list, sheetName, clazz, merge, os, options);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -261,7 +261,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportTemplate(data, templatePath, os);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -283,13 +283,16 @@ public class ExcelUtil {
.registerConverter(new ExcelBigNumberConvert())
.registerWriteHandler(new DataWriteHandler(data.getFirst().getClass()))
.build();
WriteSheet writeSheet = FesodSheet.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
// 单表多数据导出 模板格式为 {.属性}
for (T d : data) {
excelWriter.fill(d, fillConfig, writeSheet);
try {
WriteSheet writeSheet = FesodSheet.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
// 单表多数据导出 模板格式为 {.属性}
for (T d : data) {
excelWriter.fill(d, fillConfig, writeSheet);
}
} finally {
excelWriter.finish();
}
excelWriter.finish();
}
/**
@@ -311,7 +314,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportTemplateMultiList(data, templatePath, os);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -334,7 +337,7 @@ public class ExcelUtil {
ServletOutputStream os = response.getOutputStream();
exportTemplateMultiSheet(data, templatePath, os);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
throw new RuntimeException("导出Excel异常", e);
}
}
@@ -355,18 +358,21 @@ public class ExcelUtil {
// 大数值自动转换 防止失真
.registerConverter(new ExcelBigNumberConvert())
.build();
WriteSheet writeSheet = FesodSheet.writerSheet().build();
for (Map.Entry<String, Object> map : data.entrySet()) {
// 设置列表后续还有数据
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
if (map.getValue() instanceof Collection) {
// 多表导出必须使用 FillWrapper
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
} else {
excelWriter.fill(map.getValue(), fillConfig, writeSheet);
try {
WriteSheet writeSheet = FesodSheet.writerSheet().build();
for (Map.Entry<String, Object> map : data.entrySet()) {
// 设置列表后续还有数据
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
if (map.getValue() instanceof Collection) {
// 多表导出必须使用 FillWrapper
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
} else {
excelWriter.fill(map.getValue(), fillConfig, writeSheet);
}
}
} finally {
excelWriter.finish();
}
excelWriter.finish();
}
/**
@@ -386,20 +392,23 @@ public class ExcelUtil {
// 大数值自动转换 防止失真
.registerConverter(new ExcelBigNumberConvert())
.build();
for (int i = 0; i < data.size(); i++) {
WriteSheet writeSheet = FesodSheet.writerSheet(i).build();
for (Map.Entry<String, Object> map : data.get(i).entrySet()) {
// 设置列表后续还有数据
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
if (map.getValue() instanceof Collection) {
// 多表导出必须使用 FillWrapper
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
} else {
excelWriter.fill(map.getValue(), writeSheet);
try {
for (int i = 0; i < data.size(); i++) {
WriteSheet writeSheet = FesodSheet.writerSheet(i).build();
for (Map.Entry<String, Object> map : data.get(i).entrySet()) {
// 设置列表后续还有数据
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
if (map.getValue() instanceof Collection) {
// 多表导出必须使用 FillWrapper
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
} else {
excelWriter.fill(map.getValue(), writeSheet);
}
}
}
} finally {
excelWriter.finish();
}
excelWriter.finish();
}
/**

View File

@@ -31,7 +31,7 @@ public class BigNumberSerializer extends NumberSerializer {
@Override
public void serialize(Number value, JsonGenerator gen, SerializationContext provider) {
// 超出范围 序列化为字符串
if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
if (value.longValue() >= MIN_SAFE_INTEGER && value.longValue() <= MAX_SAFE_INTEGER) {
super.serialize(value, gen, provider);
} else {
gen.writeString(value.toString());

View File

@@ -33,7 +33,7 @@ public enum DataScopeType {
/**
* 自定数据权限
*/
CUSTOM("2", " #{#deptName} IN ( #{@sdss.getRoleCustom( #user.roleId )} ) ", " 1 = 0 "),
CUSTOM("2", " #{#deptName} IN ( #{@sdss.getRoleCustom( #roleId )} ) ", " 1 = 0 "),
/**
* 部门数据权限

View File

@@ -63,7 +63,7 @@ public class InjectionMetaObjectHandler implements MetaObjectHandler {
this.strictInsertFill(metaObject, "updateTime", Date.class, date);
}
} catch (Exception e) {
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_INTERNAL_ERROR);
}
}
@@ -81,17 +81,14 @@ public class InjectionMetaObjectHandler implements MetaObjectHandler {
baseEntity.setUpdateTime(current);
// 获取当前登录用户的ID并填充更新人信息
Long userId = LoginHelper.getUserId();
if (ObjectUtil.isNotNull(userId)) {
baseEntity.setUpdateBy(userId);
} else {
baseEntity.setUpdateBy(DEFAULT_USER_ID);
}
LoginUser loginUser = getLoginUser();
Long userId = ObjectUtil.isNotNull(loginUser) ? loginUser.getUserId() : DEFAULT_USER_ID;
baseEntity.setUpdateBy(userId);
} else {
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
} catch (Exception e) {
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_INTERNAL_ERROR);
}
}

View File

@@ -133,7 +133,7 @@ public class PlusDataPermissionHandler {
}
for (RoleDTO role : scopeRoles) {
user.setRoleId(role.getRoleId());
context.setVariable("roleId", role.getRoleId());
// 获取角色权限泛型
DataScopeType type = DataScopeType.findCode(role.getDataScope());
if (ObjectUtil.isNull(type)) {

View File

@@ -2,6 +2,7 @@ package org.dromara.common.mybatis.helper;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
@@ -14,6 +15,7 @@ import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 数据库助手
@@ -24,6 +26,7 @@ import java.util.List;
public class DataBaseHelper {
private static final DynamicRoutingDataSource DS = SpringUtils.getBean(DynamicRoutingDataSource.class);
private static final Map<String, DataBaseType> DB_TYPE_CACHE = new java.util.concurrent.ConcurrentHashMap<>();
/**
* 获取当前数据源对应的数据库类型
@@ -37,13 +40,17 @@ public class DataBaseHelper {
*/
public static DataBaseType getDataBaseType() {
DataSource dataSource = DS.determineDataSource();
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
String databaseProductName = metaData.getDatabaseProductName();
return DataBaseType.find(databaseProductName);
} catch (SQLException e) {
throw new RuntimeException("获取数据库类型失败", e);
}
String dsKey = DynamicDataSourceContextHolder.peek();
final String key = dsKey != null ? dsKey : "primary";
return DB_TYPE_CACHE.computeIfAbsent(key, k -> {
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
String databaseProductName = metaData.getDatabaseProductName();
return DataBaseType.find(databaseProductName);
} catch (SQLException e) {
throw new RuntimeException("获取数据库类型失败", e);
}
});
}
/**

View File

@@ -12,9 +12,10 @@ import org.dromara.common.mybatis.core.domain.DataPermissionAccess;
import org.dromara.common.core.utils.reflect.ReflectUtils;
import org.dromara.common.mybatis.annotation.DataPermission;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.function.Supplier;
/**
@@ -30,7 +31,7 @@ public class DataPermissionHelper {
private static final String DATA_PERMISSION_KEY = "data:permission";
private static final String ACCESS_KEY = "data:permission:access";
private static final ThreadLocal<Stack<Integer>> REENTRANT_IGNORE = ThreadLocal.withInitial(Stack::new);
private static final ThreadLocal<Deque<Integer>> REENTRANT_IGNORE = ThreadLocal.withInitial(ArrayDeque::new);
private static final ThreadLocal<DataPermission> PERMISSION_CACHE = new ThreadLocal<>();
@@ -116,7 +117,7 @@ public class DataPermissionHelper {
if (attribute instanceof Map map) {
return map;
}
throw new NullPointerException("data permission context type exception");
throw new IllegalStateException("data permission context type exception");
}
/**
@@ -144,7 +145,7 @@ public class DataPermissionHelper {
} else {
ignoreStrategy.setDataPermission(true);
}
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
Deque<Integer> reentrantStack = REENTRANT_IGNORE.get();
reentrantStack.push(reentrantStack.size() + 1);
}
@@ -159,7 +160,7 @@ public class DataPermissionHelper {
&& !Boolean.TRUE.equals(ignoreStrategy.getIllegalSql())
&& !Boolean.TRUE.equals(ignoreStrategy.getTenantLine())
&& CollectionUtil.isEmpty(ignoreStrategy.getOthers());
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
Deque<Integer> reentrantStack = REENTRANT_IGNORE.get();
boolean empty = reentrantStack.isEmpty() || reentrantStack.pop() == 1;
if (noOtherIgnoreStrategy && empty) {
InterceptorIgnoreHelper.clearIgnoreStrategy();