调整项目结构,集成Sa-Token、Lombok、Hutool等软件

This commit is contained in:
dataprince 2023-08-15 22:24:31 +08:00
parent c19ffbe392
commit 5ba051c16a
401 changed files with 16632 additions and 6914 deletions

227
pom.xml
View File

@ -3,22 +3,23 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-flex</artifactId> <artifactId>ruoyi-flex</artifactId>
<version>${revision}</version> <version>${revision}</version>
<name>Ruoyi-Flex</name> <name>Ruoyi-Flex</name>
<url>http://www.ruoyi.vip</url> <url> https://gitee.com/dataprince/ruoyi-flex</url>
<description>若依管理系统</description> <description>Ruoyi-Flex管理系统</description>
<properties> <properties>
<revision>4.1.3</revision> <revision>4.1.4-SNAPSHOT</revision>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version> <java.version>17</java.version>
<spring-boot.version>3.0.8</spring-boot.version> <spring-boot.version>3.1.2</spring-boot.version>
<mybatis-flex.version>1.5.3</mybatis-flex.version> <mybatis-flex.version>1.5.7</mybatis-flex.version>
<satoken.version>1.35.0.RC</satoken.version>
<mysql.version>8.0.33</mysql.version> <mysql.version>8.0.33</mysql.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<HikariCP.version>5.0.1</HikariCP.version> <HikariCP.version>5.0.1</HikariCP.version>
@ -30,7 +31,8 @@
<oshi.version>6.4.3</oshi.version> <oshi.version>6.4.3</oshi.version>
<commons.io.version>2.11.0</commons.io.version> <commons.io.version>2.11.0</commons.io.version>
<commons.collections.version>3.2.2</commons.collections.version> <commons.collections.version>3.2.2</commons.collections.version>
<poi.version>4.1.2</poi.version> <poi.version>5.2.3</poi.version>
<easyexcel.version>3.3.2</easyexcel.version>
<velocity.version>2.3</velocity.version> <velocity.version>2.3</velocity.version>
<jwt.version>0.9.1</jwt.version> <jwt.version>0.9.1</jwt.version>
<servlet-api.version>6.0.0</servlet-api.version> <servlet-api.version>6.0.0</servlet-api.version>
@ -39,14 +41,47 @@
<springdoc.version>2.1.0</springdoc.version> <springdoc.version>2.1.0</springdoc.version>
<springdoc-openapi-starter-common.version>2.1.0</springdoc-openapi-starter-common.version> <springdoc-openapi-starter-common.version>2.1.0</springdoc-openapi-starter-common.version>
<therapi-runtime-javadoc.version>0.15.0</therapi-runtime-javadoc.version> <therapi-runtime-javadoc.version>0.15.0</therapi-runtime-javadoc.version>
<lombok.version>1.18.28</lombok.version>
<mapstruct-plus.version>1.3.5</mapstruct-plus.version>
<mapstruct-plus.lombok.version>0.2.0</mapstruct-plus.lombok.version>
<hutool.version>5.8.21</hutool.version>
<redisson.version>3.23.2</redisson.version>
<lock4j.version>2.2.4</lock4j.version>
<alibaba-ttl.version>2.14.3</alibaba-ttl.version>
<!-- 插件版本 -->
<maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
<maven-war-plugin.version>3.2.2</maven-war-plugin.version>
<maven-compiler-plugin.verison>3.11.0</maven-compiler-plugin.verison> <maven-compiler-plugin.verison>3.11.0</maven-compiler-plugin.verison>
<maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version>
<flatten-maven-plugin.version>1.3.0</flatten-maven-plugin.version>
</properties> </properties>
<profiles>
<profile>
<id>dev</id>
<properties>
<!-- 环境标识,需要与配置文件的名称相对应 -->
<profiles.active>dev</profiles.active>
<logging.level>debug</logging.level>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
<logging.level>warn</logging.level>
</properties>
</profile>
</profiles>
<!-- 依赖声明 --> <!-- 依赖声明 -->
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<!-- SpringBoot的依赖配置--> <!-- SpringBoot的依赖配置-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -56,10 +91,27 @@
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
<!-- hutool 的依赖配置-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>${hutool.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- common 的依赖配置-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-bom</artifactId>
<version>${revision}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring-boot.version}</version>
</dependency> </dependency>
<!-- 数据库连接池--> <!-- 数据库连接池-->
@ -76,6 +128,30 @@
<version>${mybatis-flex.version}</version> <version>${mybatis-flex.version}</version>
</dependency> </dependency>
<!-- Sa-Token 权限认证在线文档https://sa-token.cc -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot3-starter</artifactId>
<version>${satoken.version}</version>
</dependency>
<!-- Sa-Token 整合 jwt -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-jwt</artifactId>
<version>${satoken.version}</version>
<exclusions>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-core</artifactId>
<version>${satoken.version}</version>
</dependency>
<!-- Mysql驱动包 --> <!-- Mysql驱动包 -->
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
@ -124,12 +200,30 @@
</dependency> </dependency>
<!-- excel工具 --> <!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version> <version>${poi.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- velocity代码生成使用模板 --> <!-- velocity代码生成使用模板 -->
<dependency> <dependency>
<groupId>org.apache.velocity</groupId> <groupId>org.apache.velocity</groupId>
@ -185,7 +279,6 @@
<version>${springdoc.version}</version> <version>${springdoc.version}</version>
</dependency> </dependency>
<!-- springdocV2包含对spring secuitry的支持 -->
<dependency> <dependency>
<groupId>org.springdoc</groupId> <groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-common</artifactId> <artifactId>springdoc-openapi-starter-common</artifactId>
@ -198,6 +291,45 @@
<version>${therapi-runtime-javadoc.version}</version> <version>${therapi-runtime-javadoc.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-spring-boot-starter</artifactId>
<version>${mapstruct-plus.version}</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>${redisson.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
<version>${lock4j.version}</version>
</dependency>
<!--Annotation Processor-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>${alibaba-ttl.version}</version>
</dependency>
<!-- 定时任务--> <!-- 定时任务-->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
@ -212,13 +344,6 @@
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${revision}</version>
</dependency>
<!-- 系统模块--> <!-- 系统模块-->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
@ -226,20 +351,6 @@
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-core</artifactId>
<version>${revision}</version>
</dependency>
<!-- springdoc模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-springdoc</artifactId>
<version>${revision}</version>
</dependency>
<!-- demo模块 --> <!-- demo模块 -->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
@ -252,8 +363,8 @@
<modules> <modules>
<module>ruoyi-admin</module> <module>ruoyi-admin</module>
<module>ruoyi-framework</module>
<module>ruoyi-common</module> <module>ruoyi-common</module>
<module>ruoyi-extra</module>
<module>ruoyi-modules</module> <module>ruoyi-modules</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
@ -274,7 +385,35 @@
<artifactId>therapi-runtime-javadoc-scribe</artifactId> <artifactId>therapi-runtime-javadoc-scribe</artifactId>
<version>${therapi-runtime-javadoc.version}</version> <version>${therapi-runtime-javadoc.version}</version>
</path> </path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
</path>
<path>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-processor</artifactId>
<version>${mapstruct-plus.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>${mapstruct-plus.lombok.version}</version>
</path>
<path>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId>
<version>${mybatis-flex.version}</version>
</path>
</annotationProcessorPaths> </annotationProcessorPaths>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
@ -307,6 +446,24 @@
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 关闭过滤 -->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<!-- 引入所有 匹配文件进行过滤 -->
<includes>
<include>application*</include>
<include>bootstrap*</include>
<include>banner*</include>
</includes>
<!-- 启用过滤 即该资源中的变量将会被过滤器中的值替换 -->
<filtering>true</filtering>
</resource>
</resources>
</build> </build>
<repositories> <repositories>
@ -334,4 +491,4 @@
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
</project> </project>

View File

@ -3,12 +3,13 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>ruoyi-flex</artifactId>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-flex</artifactId>
<version>${revision}</version> <version>${revision}</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging> <packaging>jar</packaging>
<artifactId>ruoyi-admin</artifactId> <artifactId>ruoyi-admin</artifactId>
<description> <description>
@ -30,16 +31,22 @@
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
</dependency> </dependency>
<!-- PostgreSql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- mybatis-flex --> <!-- mybatis-flex -->
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot-starter</artifactId> <artifactId>mybatis-flex-spring-boot-starter</artifactId>
</dependency> </dependency>
<!-- 核心模块--> <!-- system模块-->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId> <artifactId>ruoyi-system</artifactId>
</dependency> </dependency>
<!-- 定时任务--> <!-- 定时任务-->
@ -54,13 +61,6 @@
<artifactId>ruoyi-generator</artifactId> <artifactId>ruoyi-generator</artifactId>
</dependency> </dependency>
<!-- springdoc模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-springdoc</artifactId>
<version>${revision}</version>
</dependency>
<!-- demo模块 --> <!-- demo模块 -->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
@ -74,29 +74,34 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version> <version>${spring-boot.version}</version>
<configuration> <configuration>
<fork>true</fork> <!-- 如果没有该配置devtools不会生效 --> <!-- <fork>true</fork> &lt;!&ndash; 如果没有该配置devtools不会生效 &ndash;&gt;-->
</configuration> </configuration>
<executions> <!-- <executions>-->
<execution> <!-- <execution>-->
<goals> <!-- <goals>-->
<goal>repackage</goal> <!-- <goal>repackage</goal>-->
</goals> <!-- </goals>-->
</execution> <!-- </execution>-->
</executions> <!-- </executions>-->
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version> <version>${maven-jar-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration> <configuration>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName> <warName>${project.artifactId}</warName>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}</finalName> <finalName>${project.artifactId}</finalName>
</build> </build>
</project> </project>

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
/** /**
* 启动程序 * 启动程序
* *
* @author ruoyi * @author ruoyi
*/ */
@SpringBootApplication @SpringBootApplication

View File

@ -0,0 +1,151 @@
package com.ruoyi.web.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.*;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.core.domain.model.RegisterBody;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysClient;
import com.ruoyi.web.service.IAuthStrategy;
import com.ruoyi.web.service.SysLoginService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
import static com.ruoyi.system.domain.table.SysClientTableDef.SYS_CLIENT;
/**
* 认证
*
* @author Lion Li
*/
@Slf4j
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
public class AuthController {
@Resource
private final SysLoginService loginService;
@Resource
private final ISysClientService clientService;
@Resource
private final ISysUserService sysUserService;
@Resource
private final ISysPermissionService permissionService;
@Resource
private ISysMenuService menuService;
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@PostMapping("/login")
public AjaxResult login(@Validated @RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
// 授权类型和客户端id
String clientId = loginBody.getClientId();
String grantType = loginBody.getGrantType();
QueryWrapper query=QueryWrapper.create().from(SYS_CLIENT).where(SYS_CLIENT.CLIENT_ID.eq(clientId));
SysClient client = clientService.getOne(query);
// 查询不到 client client 内不包含 grantType
if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
log.info("客户端id: {} 认证类型:{} 异常!.", clientId, grantType);
return AjaxResult.error(MessageUtils.message("auth.grant.type.error"));
}
// TODO:校验租户
//loginService.checkTenant(loginBody.getTenantId());
// 生成令牌
String token =IAuthStrategy.login(loginBody, client);
ajax.put(Constants.TOKEN, token);
// 登录
return ajax;
}
/**
* 获取用户信息
*
* @return 用户信息
*/
@GetMapping("/getInfo")
public AjaxResult getInfo() {
LoginUser loginUser = LoginHelper.getLoginUser();
//TODO:多租户 超级管理员 如果重新加载用户信息需清除动态租户
SysUser user = sysUserService.selectUserById(loginUser.getUserId());
// 角色集合
Set<String> roles = permissionService.getRolePermission(user.getUserId());
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user.getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("user", user);
ajax.put("roles", roles);
ajax.put("permissions", permissions);
return ajax;
}
/**
* 获取路由信息
*
* @return 路由信息
*/
@GetMapping("/getRouters")
public AjaxResult getRouters()
{
LoginUser loginUser = LoginHelper.getLoginUser();
// 用户信息
SysUser user = sysUserService.selectUserById(loginUser.getUserId());
List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
return AjaxResult.success(menuService.buildMenus(menus));
}
/**
* 退出登录
*/
@PostMapping("/logout")
public AjaxResult logout() {
loginService.logout();
return AjaxResult.error("退出成功!");
}
/**
* 用户注册
*/
@PostMapping("LoginHelper.getUserId()")
public R<Void> register(@Validated @RequestBody RegisterBody user) {
//if (!configService.selectRegisterEnabled(user.getTenantId())) // TODO注册代码
{
return R.fail("当前系统没有开启注册功能!");
}
// registerService.register(user);
// return R.ok();
}
}

View File

@ -0,0 +1,84 @@
package com.ruoyi.web.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import java.time.Duration;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.reflect.ReflectUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.web.enums.CaptchaType;
import com.ruoyi.web.domain.vo.CaptchaVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.web.config.properties.CaptchaProperties;
/**
* 验证码操作处理
*
* @author ruoyi
*/
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController
{
private final CaptchaProperties captchaProperties;
/**
* 生成验证码
*/
@GetMapping("/captchaImage")
public AjaxResult getCode() {
CaptchaVo captchaVo = new CaptchaVo();
boolean captchaEnabled = captchaProperties.getEnable();
if (!captchaEnabled) {
captchaVo.setCaptchaEnabled(false);
return AjaxResult.success(captchaVo);
}
// 保存验证码信息
String uuid = IdUtil.simpleUUID();
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
// 生成验证码
CaptchaType captchaType = captchaProperties.getType();
boolean isMath = CaptchaType.MATH == captchaType;
Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
captcha.setGenerator(codeGenerator);
captcha.createCode();
String code = captcha.getCode();
if (isMath) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
code = exp.getValue(String.class);
}
RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
// AjaxResult ajax = AjaxResult.success();
// ajax.put("uuid", uuid);
// ajax.put("img", captcha.getImageBase64());
// return ajax;
captchaVo.setUuid(uuid);
captchaVo.setImg(captcha.getImageBase64());
return AjaxResult.success(captchaVo);
}
}

View File

@ -1,5 +1,7 @@
package com.ruoyi.web.controller.system; package com.ruoyi.web.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -11,11 +13,12 @@ import com.ruoyi.common.core.utils.StringUtils;
* *
* @author ruoyi * @author ruoyi
*/ */
@SaIgnore
@RestController @RestController
public class SysIndexController public class SysIndexController
{ {
/** 系统基础配置 */ /** 系统基础配置 */
@Autowired @Resource
private RuoYiConfig ruoyiConfig; private RuoYiConfig ruoyiConfig;
/** /**

View File

@ -1,94 +0,0 @@
package com.ruoyi.web.controller.common;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.Resource;
import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.core.config.RuoYiConfig;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.redis.RedisCache;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
/**
* 验证码操作处理
*
* @author ruoyi
*/
@RestController
public class CaptchaController
{
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysConfigService configService;
/**
* 生成验证码
*/
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException
{
AjaxResult ajax = AjaxResult.success();
boolean captchaEnabled = configService.selectCaptchaEnabled();
ajax.put("captchaEnabled", captchaEnabled);
if (!captchaEnabled)
{
return ajax;
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
String captchaType = RuoYiConfig.getCaptchaType();
if ("math".equals(captchaType))
{
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
image = captchaProducerMath.createImage(capStr);
}
else if ("char".equals(captchaType))
{
capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr);
}
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return AjaxResult.error(e.getMessage());
}
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}

View File

@ -19,11 +19,11 @@ import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileUploadUtils; import com.ruoyi.common.core.utils.file.FileUploadUtils;
import com.ruoyi.common.core.utils.file.FileUtils; import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig; import com.ruoyi.system.config.ServerConfig;
/** /**
* 通用请求处理 * 通用请求处理
* *
* @author ruoyi * @author ruoyi
*/ */
@RestController @RestController
@ -39,7 +39,7 @@ public class CommonController
/** /**
* 通用下载请求 * 通用下载请求
* *
* @param fileName 文件名称 * @param fileName 文件名称
* @param delete 是否删除 * @param delete 是否删除
*/ */

View File

@ -1,120 +0,0 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysCache;
/**
* 缓存监控
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/cache")
public class CacheController
{
@Autowired
private RedisTemplate<String, String> redisTemplate;
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception
{
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
result.put("commandStats", pieList);
return AjaxResult.success(result);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getNames")
public AjaxResult cache()
{
return AjaxResult.success(caches);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getKeys/{cacheName}")
public AjaxResult getCacheKeys(@PathVariable String cacheName)
{
Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
return AjaxResult.success(cacheKeys);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
{
String cacheValue = redisTemplate.opsForValue().get(cacheKey);
SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
return AjaxResult.success(sysCache);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheName/{cacheName}")
public AjaxResult clearCacheName(@PathVariable String cacheName)
{
Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheKey/{cacheKey}")
public AjaxResult clearCacheKey(@PathVariable String cacheKey)
{
redisTemplate.delete(cacheKey);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheAll")
public AjaxResult clearCacheAll()
{
Collection<String> cacheKeys = redisTemplate.keys("*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
}

View File

@ -1,83 +0,0 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.annotation.Log;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.core.controller.BaseController;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.core.core.page.TableDataInfo;
import com.ruoyi.common.core.core.redis.RedisCache;
import com.ruoyi.common.core.enums.BusinessType;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysUserOnlineService;
/**
* 在线用户监控
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController
{
@Autowired
private ISysUserOnlineService userOnlineService;
@Autowired
private RedisCache redisCache;
@PreAuthorize("@ss.hasPermi('monitor:online:list')")
@GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName)
{
Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
List<SysUserOnline> userOnlineList = new ArrayList<>();
for (String key : keys)
{
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
{
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
}
else if (StringUtils.isNotEmpty(ipaddr))
{
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
{
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
else
{
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}
/**
* 强退用户
*/
@PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId)
{
redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
return success();
}
}

View File

@ -1,86 +0,0 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.entity.SysMenu;
import com.ruoyi.common.core.core.domain.entity.SysUser;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
/**
* 登录验证
*
* @author ruoyi
*/
@RestController
public class SysLoginController
{
@Autowired
private SysLoginService loginService;
@Autowired
private ISysMenuService menuService;
@Autowired
private SysPermissionService permissionService;
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody)
{
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
* 获取用户信息
*
* @return 用户信息
*/
@GetMapping("getInfo")
public AjaxResult getInfo()
{
SysUser user = SecurityUtils.getLoginUser().getUser();
// 角色集合
Set<String> roles = permissionService.getRolePermission(user);
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user);
AjaxResult ajax = AjaxResult.success();
ajax.put("user", user);
ajax.put("roles", roles);
ajax.put("permissions", permissions);
return ajax;
}
/**
* 获取路由信息
*
* @return 路由信息
*/
@GetMapping("getRouters")
public AjaxResult getRouters()
{
Long userId = SecurityUtils.getUserId();
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
return AjaxResult.success(menuService.buildMenus(menus));
}
}

View File

@ -1,38 +0,0 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.core.controller.BaseController;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.model.RegisterBody;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
/**
* 注册验证
*
* @author ruoyi
*/
@RestController
public class SysRegisterController extends BaseController
{
@Autowired
private SysRegisterService registerService;
@Autowired
private ISysConfigService configService;
@PostMapping("/register")
public AjaxResult register(@RequestBody RegisterBody user)
{
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
{
return error("当前系统没有开启注册功能!");
}
String msg = registerService.register(user);
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
}

View File

@ -0,0 +1,25 @@
package com.ruoyi.web.domain.vo;
import lombok.Data;
/**
* 验证码信息
*
* @author Michelle.Chung
*/
@Data
public class CaptchaVo {
/**
* 是否开启验证码
*/
private Boolean captchaEnabled = true;
private String uuid;
/**
* 验证码图片
*/
private String img;
}

View File

@ -0,0 +1,54 @@
package com.ruoyi.web.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 登录验证信息
*
* @author Michelle.Chung
*/
@Data
public class LoginVo {
/**
* 授权令牌
*/
@JsonProperty("access_token")
private String accessToken;
/**
* 刷新令牌
*/
@JsonProperty("refresh_token")
private String refreshToken;
/**
* 授权令牌 access_token 的有效期
*/
@JsonProperty("expire_in")
private Long expireIn;
/**
* 刷新令牌 refresh_token 的有效期
*/
@JsonProperty("refresh_expire_in")
private Long refreshExpireIn;
/**
* 应用id
*/
@JsonProperty("client_id")
private String clientId;
/**
* 令牌权限
*/
private String scope;
/**
* 用户 openid
*/
private String openid;
}

View File

@ -0,0 +1,45 @@
package com.ruoyi.web.service;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.system.domain.SysClient;
/**
* 授权策略
*
* @author Michelle.Chung
*/
public interface IAuthStrategy {
String BASE_NAME = "AuthStrategy";
/**
* 登录
*/
static String login(LoginBody loginBody, SysClient client) {
// 授权类型和客户端id
String clientId = loginBody.getClientId();
String grantType = loginBody.getGrantType();
String beanName = grantType + BASE_NAME;
if (!SpringUtils.containsBean(beanName)) {
throw new ServiceException("授权类型不正确!");
}
IAuthStrategy instance = SpringUtils.getBean(beanName);
instance.validate(loginBody);
return instance.login(clientId, loginBody, client);
}
/**
* 参数校验
*/
void validate(LoginBody loginBody);
/**
* 登录
*/
String login(String clientId, LoginBody loginBody, SysClient client);
}

View File

@ -0,0 +1,175 @@
package com.ruoyi.web.service;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.constant.*;
import com.ruoyi.common.core.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.enums.LoginType;
import com.ruoyi.common.core.exception.user.*;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.log.event.LogininforEvent;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.common.tenant.helper.TenantHelper;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.vo.SysUserVo;
import com.ruoyi.system.service.ISysPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
/**
* 登录校验方法
*
* @author ruoyi
*/
@RequiredArgsConstructor
@Slf4j
@Service
public class SysLoginService {
@Value("${user.password.maxRetryCount}")
private Integer maxRetryCount;
@Value("${user.password.lockTime}")
private Integer lockTime;
private final ISysPermissionService permissionService;
@Autowired
private ISysUserService userService;
/**
* 登录校验
*/
public void checkLogin(LoginType loginType, Long tenantId, String username, Supplier<Boolean> supplier) {
String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
String loginFail = Constants.LOGIN_FAIL;
// 获取用户登录错误次数默认为0 (可自定义限制策略 例如: key + username + ip)
int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
// 锁定时间内登录 则踢出
if (errorNumber >= maxRetryCount) {
recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
}
if (supplier.get()) {
// 错误次数递增
errorNumber++;
RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
// 达到规定错误次数 则锁定登录
if (errorNumber >= maxRetryCount) {
recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
} else {
// 未达到规定错误次数
recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
throw new UserException(loginType.getRetryLimitCount(), errorNumber);
}
}
// 登录成功 清空错误次数
RedisUtils.deleteObject(errorKey);
}
/**
* 校验租户
*
* @param tenantId 租户ID
*/
public void checkTenant(String tenantId) {
if (!TenantHelper.isEnable()) {
return;
}
if (TenantConstants.DEFAULT_TENANT_ID.equals(tenantId)) {
return;
}
//TODO:完善heckTenant功能
}
/**
* 构建登录用户
*/
public LoginUser buildLoginUser(SysUser user) {
LoginUser loginUser = new LoginUser();
loginUser.setTenantId(user.getTenantId());
loginUser.setUserId(user.getUserId());
loginUser.setDeptId(user.getDeptId());
loginUser.setUsername(user.getUserName());
loginUser.setNickname(user.getNickName());
loginUser.setUserType(user.getUserType());
loginUser.setMenuPermission(permissionService.getMenuPermission(user.getUserId()));
loginUser.setRolePermission(permissionService.getRolePermission(user.getUserId()));
loginUser.setDeptName(ObjectUtil.isNull(user.getDept()) ? "" : user.getDept().getDeptName());
List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
loginUser.setRoles(roles);
return loginUser;
}
/**
* 记录登录信息
*
* @param userId 用户ID
*/
public void recordLoginInfo(Long userId) {
SysUser sysUser = new SysUser();
sysUser.setUserId(userId);
sysUser.setLoginIp(ServletUtils.getClientIP());
sysUser.setLoginDate(DateUtils.getNowDate());
sysUser.setUpdateBy(userId);
userService.updateUserProfile(sysUser);
}
/**
* 记录租户登录信息
*
* @param tenantId 租户ID
* @param username 用户名
* @param status 状态
* @param message 消息内容
*/
public void recordLogininfor(Long tenantId, String username, String status, String message) {
LogininforEvent logininforEvent = new LogininforEvent();
logininforEvent.setTenantId(tenantId);
logininforEvent.setUsername(username);
logininforEvent.setStatus(status);
logininforEvent.setMessage(message);
logininforEvent.setRequest(ServletUtils.getRequest());
SpringUtils.context().publishEvent(logininforEvent);
}
/**
* 退出登录
*/
public void logout() {
try {
LoginUser loginUser = LoginHelper.getLoginUser();
if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
// 超级管理员 登出清除动态租户
TenantHelper.clearDynamic();
}
recordLogininfor(loginUser.getTenantId(), loginUser.getUsername(), Constants.LOGOUT, MessageUtils.message("user.logout.success"));
} catch (NotLoginException ignored) {
} finally {
try {
StpUtil.logout();
} catch (NotLoginException ignored) {
}
}
}
}

View File

@ -0,0 +1,115 @@
package com.ruoyi.web.service;
import cn.dev33.satoken.secure.BCrypt;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.enums.UserType;
import com.ruoyi.common.core.exception.user.UserException;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.log.event.LogininforEvent;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.web.config.properties.CaptchaProperties;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.bo.SysUserBo;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.core.domain.model.RegisterBody;
import com.ruoyi.common.core.exception.user.CaptchaException;
import com.ruoyi.common.core.exception.user.CaptchaExpireException;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.stereotype.Service;
/**
* 注册校验方法
*
* @author ruoyi
*/
@RequiredArgsConstructor
@Service
public class SysRegisterService
{
@Resource
private ISysUserService userService;
@Resource
private ISysConfigService configService;
private final CaptchaProperties captchaProperties;
/**
* 注册
*/
public void register(RegisterBody registerBody)
{
Long tenantId = registerBody.getTenantId();
String username = registerBody.getUsername();
String password = registerBody.getPassword();
// 校验用户类型是否存在
String userType = UserType.getUserType(registerBody.getUserType()).getUserType();
boolean captchaEnabled = captchaProperties.getEnable();
// 验证码开关
if (captchaEnabled) {
validateCaptcha(tenantId, username, registerBody.getCode(), registerBody.getUuid());
}
SysUser sysUser = new SysUser();
sysUser.setUserName(username);
sysUser.setNickName(username);
sysUser.setPassword(BCrypt.hashpw(password));
sysUser.setUserType(userType);
if (!userService.checkUserNameUnique(sysUser)) {
throw new UserException("user.register.save.error", username);
}
boolean regFlag = userService.registerUser(sysUser, tenantId);
if (!regFlag) {
throw new UserException("user.register.error");
}
recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
}
/**
* 校验验证码
*
* @param tenantId 租户ID
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
public void validateCaptcha(Long tenantId, String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha)) {
recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
/**
* 记录登录信息
*
* @param tenantId 租户ID
* @param username 用户名
* @param status 状态
* @param message 消息内容
* @return
*/
private void recordLogininfor(Long tenantId, String username, String status, String message) {
LogininforEvent logininforEvent = new LogininforEvent();
logininforEvent.setTenantId(tenantId);
logininforEvent.setUsername(username);
logininforEvent.setStatus(status);
logininforEvent.setMessage(message);
logininforEvent.setRequest(ServletUtils.getRequest());
SpringUtils.context().publishEvent(logininforEvent);
}
}

View File

@ -0,0 +1,112 @@
package com.ruoyi.web.service.impl;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.core.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.core.enums.LoginType;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.user.CaptchaExpireException;
import com.ruoyi.common.core.exception.user.UserException;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ValidatorUtils;
import com.ruoyi.common.core.validate.auth.EmailGroup;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.system.domain.SysClient;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.service.IAuthStrategy;
import com.ruoyi.web.service.SysLoginService;
import org.springframework.stereotype.Service;
/**
* 邮件认证策略
*
* @author Michelle.Chung
*/
@Slf4j
@Service("email" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class EmailAuthStrategy implements IAuthStrategy {
private final SysLoginService loginService;
private final SysUserMapper userMapper;
@Override
public void validate(LoginBody loginBody) {
ValidatorUtils.validate(loginBody, EmailGroup.class);
}
@Override
public String login(String clientId, LoginBody loginBody, SysClient client) {
Long tenantId = loginBody.getTenantId();
String email = loginBody.getEmail();
String emailCode = loginBody.getEmailCode();
// 通过邮箱查找用户
SysUser user = loadUserByEmail(tenantId, email);
loginService.checkLogin(LoginType.EMAIL, tenantId, user.getUserName(), () -> !validateEmailCode(tenantId, email, emailCode));
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
LoginUser loginUser = loginService.buildLoginUser(user);
SaLoginModel model = new SaLoginModel();
model.setDevice(client.getDeviceType());
// 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
// 例如: 后台用户30分钟过期 app用户1天过期
model.setTimeout(client.getTimeout());
model.setActiveTimeout(client.getActiveTimeout());
model.setExtra(LoginHelper.CLIENT_KEY, clientId);
// 生成token
LoginHelper.login(loginUser, model);
loginService.recordLogininfor(loginUser.getTenantId(), user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
loginService.recordLoginInfo(user.getUserId());
// LoginVo loginVo = new LoginVo();
// loginVo.setAccessToken(StpUtil.getTokenValue());
// loginVo.setExpireIn(StpUtil.getTokenTimeout());
// loginVo.setClientId(clientId);
// return loginVo;
return StpUtil.getTokenValue();
}
/**
* 校验邮箱验证码
*/
private boolean validateEmailCode(Long tenantId, String email, String emailCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + email);
if (StringUtils.isBlank(code)) {
loginService.recordLogininfor(tenantId, email, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
return code.equals(emailCode);
}
private SysUser loadUserByEmail(Long tenantId, String email) {
// SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
// .select(SysUser::getEmail, SysUser::getStatus)
// .eq(TenantHelper.isEnable(), SysUser::getTenantId, tenantId)
// .eq(SysUser::getEmail, email));
SysUser user =userMapper.selectUserByEmail(email);
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", email);
throw new UserException("user.not.exists", email);
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
log.info("登录用户:{} 已被停用.", email);
throw new UserException("user.blocked", email);
}
// if (TenantHelper.isEnable()) {
// return userMapper.selectTenantUserByEmail(email, tenantId);
// }
return user;
}
}

View File

@ -0,0 +1,137 @@
package com.ruoyi.web.service.impl;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.system.service.ISysUserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.core.enums.LoginType;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.user.CaptchaException;
import com.ruoyi.common.core.exception.user.CaptchaExpireException;
import com.ruoyi.common.core.exception.user.UserException;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ValidatorUtils;
import com.ruoyi.common.core.validate.auth.PasswordGroup;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.common.web.config.properties.CaptchaProperties;
import com.ruoyi.system.domain.SysClient;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.vo.SysUserVo;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.domain.vo.LoginVo;
import com.ruoyi.web.service.IAuthStrategy;
import com.ruoyi.web.service.SysLoginService;
import org.springframework.stereotype.Service;
/**
* 密码认证策略
*
* @author Michelle.Chung
*/
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {
private final CaptchaProperties captchaProperties;
private final SysLoginService loginService;
@Resource
private ISysUserService userService;
//private final SysUserMapper userMapper;
@Override
public void validate(LoginBody loginBody) {
ValidatorUtils.validate(loginBody, PasswordGroup.class);
}
@Override
public String login(String clientId, LoginBody loginBody, SysClient client) {
Long tenantId = loginBody.getTenantId();
String username = loginBody.getUsername();
String password = loginBody.getPassword();
String code = loginBody.getCode();
String uuid = loginBody.getUuid();
boolean captchaEnabled = captchaProperties.getEnable();
// 验证码开关
if (captchaEnabled) {
validateCaptcha(tenantId, username, code, uuid);
}
SysUser user = loadUserByUsername(tenantId, username);
loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !BCrypt.checkpw(password, user.getPassword()));
// 此处可根据登录用户的数据不同 自行创建 loginUser
LoginUser loginUser = loginService.buildLoginUser(user);
SaLoginModel model = new SaLoginModel();
model.setDevice(client.getDeviceType());
// 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
// 例如: 后台用户30分钟过期 app用户1天过期
model.setTimeout(client.getTimeout());
model.setActiveTimeout(client.getActiveTimeout());
model.setExtra(LoginHelper.CLIENT_KEY, clientId);
// 生成token
LoginHelper.login(loginUser, model);
loginService.recordLogininfor(loginUser.getTenantId(), username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
loginService.recordLoginInfo(user.getUserId());
// LoginVo loginVo = new LoginVo();
// loginVo.setAccessToken(StpUtil.getTokenValue());
// loginVo.setExpireIn(StpUtil.getTokenTimeout());
// loginVo.setClientId(clientId);
// return loginVo;
return StpUtil.getTokenValue();
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
private void validateCaptcha(Long tenantId, String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha)) {
loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
private SysUser loadUserByUsername(Long tenantId, String username) {
//TODO:以后根据tenantId条件过滤查询
SysUser user = userService.selectUserByUserName(username);
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", username);
throw new UserException("user.not.exists", username);
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
log.info("登录用户:{} 已被停用.", username);
throw new UserException("user.blocked", username);
}
// if (TenantHelper.isEnable()) {
// return userMapper.selectTenantUserByUserName(username, tenantId);
// }
return user;
}
}

View File

@ -1,14 +1,49 @@
# 数据源配置 # 数据源及mybatis、mybatis-flex配置
mybatis-flex: mybatis-flex:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 不支持多包, 如有需要可在注解配置 或 提升扫包等级com.**.**.mapper
mapperPackage: com.ruoyi.**.mapper
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapper-locations: classpath*:mapper/**/*Mapper.xml
cacheEnabled: true
useGeneratedKeys: true
defaultExecutorType: SIMPLE
#本部分Configuration的配置都为 MyBatis 原生支持的配置,有关配置请参考:https://mybatis.org/mybatis-3/zh/configuration.html#%E8%AE%BE%E7%BD%AE%EF%BC%88settings%EF%BC%89
configuration:
# 自动驼峰命名规则camel case映射
mapUnderscoreToCamelCase: true
# MyBatis 自动映射策略
# NONE不启用 PARTIAL只对非嵌套 resultMap 自动映射 FULL对所有 resultMap 自动映射
autoMappingBehavior: FULL
# MyBatis 自动映射时未知列或未知属性处理策
# NONE不做处理 WARNING打印相关警告 FAILING抛出异常和详细信息
autoMappingUnknownColumnBehavior: NONE
# 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
# 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
# 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.slf4j.Slf4jImpl
# MyBatis-Flex全局配置
global-config:
# 是否控制台打印 MyBatis-Flex 的 LOGO 及版本号
print-banner: false
# 逻辑删除数据存在标记值
normal-value-of-logic-delete: 0
# 逻辑删除数据存在标记值
deleted-value-of-logic-delete: 1
datasource: datasource:
# 数据源-1 # 数据源-1
PrimaryDS: PrimaryDS:
# 指定为HikariDataSource # 指定为HikariDataSource
type: com.zaxxer.hikari.HikariDataSource type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
username: root username: root123
password: Root@369 password: Root@369---0000
hikari: hikari:
#连接池名 #连接池名
@ -32,5 +67,42 @@ mybatis-flex:
# 连接测试query # 连接测试query
connection-test-query: SELECT 1 connection-test-query: SELECT 1
# redis 单机配置(单机与集群只能开启一个另一个需要注释掉)
spring.data:
redis:
# 地址
host: localhost
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 密码(如没有密码请注释掉)
# password:
# 连接超时时间
timeout: 10s
# 是否开启ssl
ssl.enabled: false
redisson:
# redis key前缀
keyPrefix:
# 线程池数量
threads: 4
# Netty线程池数量
nettyThreads: 8
# 单节点配置
singleServerConfig:
# 客户端名称
clientName: ${ruoyi.name}
# 最小空闲连接数
connectionMinimumIdleSize: 8
# 连接池大小
connectionPoolSize: 32
# 连接空闲超时,单位:毫秒
idleConnectionTimeout: 10000
# 命令等待超时,单位:毫秒
timeout: 3000
# 发布和订阅连接池大小
subscriptionConnectionPoolSize: 50

View File

@ -0,0 +1,110 @@
# 临时文件存储位置 避免临时文件被系统清理报错
spring.servlet.multipart.location: /ruoyi/server/temp
# 数据源及mybatis、mybatis-flex配置
mybatis-flex:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapper-locations: classpath*:mapper/**/*Mapper.xml
cacheEnabled: true
useGeneratedKeys: true
defaultExecutorType: SIMPLE
#本部分Configuration的配置都为 MyBatis 原生支持的配置,有关配置请参考:https://mybatis.org/mybatis-3/zh/configuration.html#%E8%AE%BE%E7%BD%AE%EF%BC%88settings%EF%BC%89
configuration:
# 自动驼峰命名规则camel case映射
mapUnderscoreToCamelCase: true
# MyBatis 自动映射策略
# NONE不启用 PARTIAL只对非嵌套 resultMap 自动映射 FULL对所有 resultMap 自动映射
autoMappingBehavior: FULL
# MyBatis 自动映射时未知列或未知属性处理策
# NONE不做处理 WARNING打印相关警告 FAILING抛出异常和详细信息
autoMappingUnknownColumnBehavior: NONE
# 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
# 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
# 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.slf4j.Slf4jImpl
# MyBatis-Flex全局配置
global-config:
# 是否控制台打印 MyBatis-Flex 的 LOGO 及版本号
print-banner: false
# 逻辑删除数据存在标记值
normal-value-of-logic-delete: 0
# 逻辑删除数据存在标记值
deleted-value-of-logic-delete: 1
datasource:
# 数据源-1
PrimaryDS:
# 指定为HikariDataSource
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
username: root123
password: Root@369---0000
hikari:
#连接池名
pool-name: HikariCP-PrimaryDS
#最小空闲连接数
minimum-idle: 10
# 空闲连接存活最大时间默认10分钟
idle-timeout: 600000
# 连接池最大连接数默认是10
maximum-pool-size: 20
# 此属性控制从池返回的连接的默认自动提交行为,默认值true
auto-commit: true
# 此属性控制池中连接的最长生命周期值0表示无限生命周期默认30分钟
max-lifetime: 1800000
# 数据库连接超时时间,默认30秒
connection-timeout: 30000
# 校验超时时间
validationTimeout: 5000
# 多久检查一次连接的活性
keepaliveTime: 30000
# 连接测试query
connection-test-query: SELECT 1
# redis 单机配置(单机与集群只能开启一个另一个需要注释掉)
spring.data:
redis:
# 地址
host: localhost
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 密码(如没有密码请注释掉)
# password:
# 连接超时时间
timeout: 10s
# 是否开启ssl
ssl.enabled: false
redisson:
# redis key前缀
keyPrefix:
# 线程池数量
threads: 16
# Netty线程池数量
nettyThreads: 32
# 单节点配置
singleServerConfig:
# 客户端名称
clientName: ${ruoyi.name}
# 最小空闲连接数
connectionMinimumIdleSize: 32
# 连接池大小
connectionPoolSize: 64
# 连接空闲超时,单位:毫秒
idleConnectionTimeout: 10000
# 命令等待超时,单位:毫秒
timeout: 3000
# 发布和订阅连接池大小
subscriptionConnectionPoolSize: 50

View File

@ -3,7 +3,7 @@ ruoyi:
# 名称 # 名称
name: RuoYi-Flex name: RuoYi-Flex
# 版本 # 版本
version: 4.1.3 version: 4.1.4-SNAPSHOT
# 版权年份 # 版权年份
copyrightYear: 2023 copyrightYear: 2023
# 实例演示开关 # 实例演示开关
@ -12,8 +12,18 @@ ruoyi:
profile: D:/ruoyi/uploadPath profile: D:/ruoyi/uploadPath
# 获取ip地址开关 # 获取ip地址开关
addressEnabled: false addressEnabled: false
# 验证码类型 math 数字计算 char 字符验证
captchaType: math captcha:
enable: true
# 页面 <参数设置> 可开启关闭 验证码校验
# 验证码类型 math 数组计算 char 字符验证
type: MATH
# line 线段干扰 circle 圆圈干扰 shear 扭曲干扰
category: CIRCLE
# 数字验证码位数
numberLength: 1
# 字符验证码长度
charLength: 4
# 开发环境配置 # 开发环境配置
server: server:
@ -43,6 +53,7 @@ logging:
level: level:
com.ruoyi: debug com.ruoyi: debug
org.springframework: warn org.springframework: warn
config: classpath:logback.xml
# 用户配置 # 用户配置
user: user:
@ -54,12 +65,14 @@ user:
# Spring配置 # Spring配置
spring: spring:
application:
name: ${ruoyi.name}
# 资源信息 # 资源信息
messages: messages:
# 国际化资源文件路径 # 国际化资源文件路径
basename: i18n/messages basename: i18n/messages
profiles: profiles:
active: dev active: @profiles.active@
# 文件上传 # 文件上传
servlet: servlet:
multipart: multipart:
@ -67,33 +80,25 @@ spring:
max-file-size: 10MB max-file-size: 10MB
# 设置总上传的文件大小 # 设置总上传的文件大小
max-request-size: 20MB max-request-size: 20MB
mvc:
format:
date-time: yyyy-MM-dd HH:mm:ss
jackson:
# 日期格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
# 格式化输出
indent_output: false
# 忽略无法转换的对象
fail_on_empty_beans: false
deserialization:
# 允许对象忽略json中不存在的属性
fail_on_unknown_properties: false
# 服务模块 # 服务模块
devtools: devtools:
restart: restart:
# 热部署开关 # 热部署开关
enabled: true enabled: true
# redis 配置
redis:
# 地址
host: localhost
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# token配置 # token配置
token: token:
@ -104,21 +109,6 @@ token:
# 令牌有效期默认30分钟 # 令牌有效期默认30分钟
expireTime: 30 expireTime: 30
# MyBatis配置
mybatis-flex:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapper-locations: classpath*:mapper/**/*Mapper.xml
cacheEnabled: true
useGeneratedKeys: true
defaultExecutorType: SIMPLE
configuration:
# 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
# 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
# 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.slf4j.Slf4jImpl
# PageHelper分页插件 # PageHelper分页插件
pagehelper: pagehelper:
helperDialect: mysql helperDialect: mysql
@ -143,6 +133,25 @@ springdoc:
enabled: true #开启/禁止api-docs, prod可以设置为false enabled: true #开启/禁止api-docs, prod可以设置为false
use-management-port: false use-management-port: false
enable-spring-security: true enable-spring-security: true
info:
# 标题
title: 'Ruoyi-Flex API Doc'
# 描述
description: 'Ruoyi-Flex SrpingDoc demo'
# 版本
version: '版本号: ${ruoyi.version}'
# 作者信息
contact:
name: 数据小王子
email: 738981257@qq.com
url: https://gitee.com/dataprince/ruoyi-flex
components:
# 鉴权方式配置
security-schemes:
apiKey:
type: APIKEY
in: HEADER
name: ${sa-token.token-name}
# 防止XSS攻击 # 防止XSS攻击
xss: xss:
@ -152,3 +161,79 @@ xss:
excludes: /system/notice excludes: /system/notice
# 匹配链接 # 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*,/demo/* urlPatterns: /system/*,/monitor/*,/tool/*,/demo/*
# 全局线程池相关配置
thread-pool:
# 是否开启线程池
enabled: false
# 队列最大长度
queueCapacity: 128
# 线程池维护线程所允许的空闲时间
keepAliveSeconds: 300
# 分布式锁 lock4j 全局配置
lock4j:
# 获取分布式锁超时时间,默认为 3000 毫秒
acquire-timeout: 3000
# 分布式锁的超时时间,默认为 30 秒
expire: 30000
# Sa-Token配置
sa-token:
# token名称 (同时也是cookie名称)
token-name: Authorization
# token固定超时 设为七天 (必定过期) 单位: 秒
timeout: 604800
# 多端不同 token 有效期 可查看 LoginHelper.loginByDevice 方法自定义
# token最低活跃时间 (指定时间无操作就过期) 单位: 秒
active-timeout: 1800
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
is-concurrent: true
# 在多人登录同一账号时是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
is-share: false
# token 风格默认可取值uuid、simple-uuid、random-32、random-64、random-128、tik
token-style: uuid
# 是否输出操作日志
is-log: true
# jwt秘钥
jwt-secret-key: abcdefghijklmnopqrstuvwxyz
# security配置
security:
# 排除路径
excludes:
# 静态资源
- /*.html
- /**/*.html
- /**/*.css
- /**/*.js
# 公共路径
- /favicon.ico
- /error
# swagger 文档配置
- /*/api-docs
- /*/api-docs/**
# actuator 监控配置
- /actuator
- /actuator/**
# 其它链接
- /login
- /register
- /captchaImage
- /captcha/get
- /captcha/check
# 多租户配置
tenant:
# 是否开启
enable: false
# 排除表
excludes:
- sys_menu
- sys_tenant
- sys_tenant_package
- sys_role_dept
- sys_role_menu
- sys_user_post
- sys_user_role
- sys_client

View File

@ -2,33 +2,38 @@
not.null=* 必须填写 not.null=* 必须填写
user.jcaptcha.error=验证码错误 user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效 user.jcaptcha.expire=验证码已失效
user.not.exists=用户不存在/密码错误 user.not.exists=对不起, 您的账号:{0} 不存在.
user.password.not.match=用户不存在/密码错误 user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次 user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟 user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号已被删除 user.password.delete=对不起,您的账号{0} 已被删除
user.blocked=用户已封禁,请联系管理员 user.blocked=对不起,您的账号:{0} 已禁用,请联系管理员
role.blocked=角色已封禁,请联系管理员 role.blocked=角色已封禁,请联系管理员
login.blocked=很遗憾访问IP已被列入系统黑名单
user.logout.success=退出成功 user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间 length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.blank=用户名不能为空
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头 user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头
user.username.length.valid=账户长度必须在{min}到{max}个字符之间
user.password.not.blank=用户密码不能为空
user.password.length.valid=用户密码长度必须在{min}到{max}个字符之间
user.password.not.valid=* 5-50个字符 user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误 user.email.not.valid=邮箱格式错误
user.email.not.blank=邮箱不能为空
user.phonenumber.not.blank=用户手机号不能为空
user.mobile.phone.number.not.valid=手机号格式错误 user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功 user.login.success=登录成功
user.register.success=注册成功 user.register.success=注册成功
user.register.save.error=保存用户 {0} 失败,注册账号已存在
user.register.error=注册失败,请联系系统管理人员
user.notfound=请重新登录 user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录 user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录 user.unknown.error=未知错误,请重新登录
auth.grant.type.error=认证权限类型错误
auth.grant.type.not.blank=认证权限类型不能为空
auth.clientid.not.blank=认证客户端id不能为空
##文件上传消息 ##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB
upload.filename.exceed.length=上传的文件名最长{0}个字符 upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限 ##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}] no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}] no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
@ -36,3 +41,17 @@ no.update.permission=您没有修改数据的权限,请联系管理员添加
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}] no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}] no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}] no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]
repeat.submit.message=不允许重复提交,请稍候再试
rate.limiter.message=访问过于频繁,请稍候再试
sms.code.not.blank=短信验证码不能为空
sms.code.retry.limit.count=短信验证码输入错误{0}次
sms.code.retry.limit.exceed=短信验证码输入错误{0}次,帐户锁定{1}分钟
email.code.not.blank=邮箱验证码不能为空
email.code.retry.limit.count=邮箱验证码输入错误{0}次
email.code.retry.limit.exceed=邮箱验证码输入错误{0}次,帐户锁定{1}分钟
xcx.code.not.blank=小程序code不能为空
##租户
tenant.number.not.blank=租户编号不能为空
tenant.not.exists=对不起, 您的租户不存在,请联系管理员
tenant.blocked=对不起,您的租户已禁用,请联系管理员
tenant.expired=对不起,您的租户已过期,请联系管理员

View File

@ -0,0 +1,57 @@
#错误消息
not.null=* Required fill in
user.jcaptcha.error=Captcha error
user.jcaptcha.expire=Captcha invalid
user.not.exists=Sorry, your account: {0} does not exist
user.password.not.match=User does not exist/Password error
user.password.retry.limit.count=Password input error {0} times
user.password.retry.limit.exceed=Password input error {0} times, account locked for {1} minutes
user.password.delete=Sorry, your account{0} has been deleted
user.blocked=Sorry, your account: {0} has been disabled. Please contact the administrator
role.blocked=Role disabledplease contact administrators
user.logout.success=Exit successful
length.not.valid=The length must be between {min} and {max} characters
user.username.not.blank=Username cannot be blank
user.username.not.valid=* 2 to 20 chinese characters, letters, numbers or underscores, and must start with a non number
user.username.length.valid=Account length must be between {min} and {max} characters
user.password.not.blank=Password cannot be empty
user.password.length.valid=Password length must be between {min} and {max} characters
user.password.not.valid=* 5-50 characters
user.email.not.valid=Mailbox format error
user.email.not.blank=Mailbox cannot be blank
user.phonenumber.not.blank=Phone number cannot be blank
user.mobile.phone.number.not.valid=Phone number format error
user.login.success=Login successful
user.register.success=Register successful
user.register.save.error=Failed to save user {0}, The registered account already exists
user.register.error=Register failed, please contact system administrator
user.notfound=Please login again
user.forcelogout=The administrator is forced to exitplease login again
user.unknown.error=Unknown error, please login again
auth.grant.type.error=Auth grant type error
auth.grant.type.not.blank=Auth grant type cannot be blank
auth.clientid.not.blank=Auth clientid cannot be blank
##文件上传消息
upload.exceed.maxSize=The uploaded file size exceeds the limit file size<br/>the maximum allowed file size is{0}MB
upload.filename.exceed.length=The maximum length of uploaded file name is {0} characters
##权限
no.permission=You do not have permission to the dataplease contact your administrator to add permissions [{0}]
no.create.permission=You do not have permission to create dataplease contact your administrator to add permissions [{0}]
no.update.permission=You do not have permission to modify dataplease contact your administrator to add permissions [{0}]
no.delete.permission=You do not have permission to delete dataplease contact your administrator to add permissions [{0}]
no.export.permission=You do not have permission to export dataplease contact your administrator to add permissions [{0}]
no.view.permission=You do not have permission to view dataplease contact your administrator to add permissions [{0}]
repeat.submit.message=Repeat submit is not allowed, please try again later
rate.limiter.message=Visit too frequently, please try again later
sms.code.not.blank=Sms code cannot be blank
sms.code.retry.limit.count=Sms code input error {0} times
sms.code.retry.limit.exceed=Sms code input error {0} times, account locked for {1} minutes
email.code.not.blank=Email code cannot be blank
email.code.retry.limit.count=Email code input error {0} times
email.code.retry.limit.exceed=Email code input error {0} times, account locked for {1} minutes
xcx.code.not.blank=Mini program code cannot be blank
##租户
tenant.number.not.blank=Tenant number cannot be blank
tenant.not.exists=Sorry, your tenant does not exist. Please contact the administrator
tenant.blocked=Sorry, your tenant is disabled. Please contact the administrator
tenant.expired=Sorry, your tenant has expired. Please contact the administrator.

View File

@ -0,0 +1,57 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=对不起, 您的账号:{0} 不存在.
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号:{0} 已被删除
user.blocked=对不起,您的账号:{0} 已禁用,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.blank=用户名不能为空
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头
user.username.length.valid=账户长度必须在{min}到{max}个字符之间
user.password.not.blank=用户密码不能为空
user.password.length.valid=用户密码长度必须在{min}到{max}个字符之间
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.email.not.blank=邮箱不能为空
user.phonenumber.not.blank=用户手机号不能为空
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.register.save.error=保存用户 {0} 失败,注册账号已存在
user.register.error=注册失败,请联系系统管理人员
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
auth.grant.type.error=认证权限类型错误
auth.grant.type.not.blank=认证权限类型不能为空
auth.clientid.not.blank=认证客户端id不能为空
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]
repeat.submit.message=不允许重复提交,请稍候再试
rate.limiter.message=访问过于频繁,请稍候再试
sms.code.not.blank=短信验证码不能为空
sms.code.retry.limit.count=短信验证码输入错误{0}次
sms.code.retry.limit.exceed=短信验证码输入错误{0}次,帐户锁定{1}分钟
email.code.not.blank=邮箱验证码不能为空
email.code.retry.limit.count=邮箱验证码输入错误{0}次
email.code.retry.limit.exceed=邮箱验证码输入错误{0}次,帐户锁定{1}分钟
xcx.code.not.blank=小程序code不能为空
##租户
tenant.number.not.blank=租户编号不能为空
tenant.not.exists=对不起, 您的租户不存在,请联系管理员
tenant.blocked=对不起,您的租户已禁用,请联系管理员
tenant.expired=对不起,您的租户已过期,请联系管理员

View File

@ -8,14 +8,25 @@
<version>${revision}</version> <version>${revision}</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules> <modules>
<module>ruoyi-common-bom</module>
<module>ruoyi-common-core</module> <module>ruoyi-common-core</module>
<module>ruoyi-common-springdoc</module> <module>ruoyi-common-excel</module>
<module>ruoyi-common-json</module>
<module>ruoyi-common-log</module>
<module>ruoyi-common-orm</module>
<module>ruoyi-common-ratelimiter</module>
<module>ruoyi-common-redis</module>
<module>ruoyi-common-security</module>
<module>ruoyi-common-springdoc</module>
<module>ruoyi-common-tenant</module>
<module>ruoyi-common-translation</module>
<module>ruoyi-common-web</module>
</modules> </modules>
<artifactId>ruoyi-common</artifactId> <artifactId>ruoyi-common</artifactId>
<packaging>pom</packaging>
<description> <description>
ruoyi-common 公共模块 ruoyi-common 公共模块

View File

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-bom</artifactId>
<version>${revision}</version>
<packaging>pom</packaging>
<description>
ruoyi-common-bom common依赖项
</description>
<properties>
<revision>4.1.4-SNAPSHOT</revision>
</properties>
<dependencyManagement>
<dependencies>
<!-- 核心模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-core</artifactId>
<version>${revision}</version>
</dependency>
<!-- excel模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-excel</artifactId>
<version>${revision}</version>
</dependency>
<!-- 序列化模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-json</artifactId>
<version>${revision}</version>
</dependency>
<!-- 日志模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-log</artifactId>
<version>${revision}</version>
</dependency>
<!-- 数据库映射模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-orm</artifactId>
<version>${revision}</version>
</dependency>
<!-- 限流公共服务 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-ratelimiter</artifactId>
<version>${revision}</version>
</dependency>
<!-- 缓存服务 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-redis</artifactId>
<version>${revision}</version>
</dependency>
<!-- 安全模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-security</artifactId>
<version>${revision}</version>
</dependency>
<!-- 接口模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-springdoc</artifactId>
<version>${revision}</version>
</dependency>
<!-- 多租户模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-tenant</artifactId>
<version>${revision}</version>
</dependency>
<!-- 翻译模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-translation</artifactId>
<version>${revision}</version>
</dependency>
<!-- web服务 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-web</artifactId>
<version>${revision}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

@ -3,11 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>ruoyi-common</artifactId>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
<version>${revision}</version> <version>${revision}</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>ruoyi-common-core</artifactId> <artifactId>ruoyi-common-core</artifactId>
@ -35,24 +36,6 @@
<artifactId>spring-web</artifactId> <artifactId>spring-web</artifactId>
</dependency> </dependency>
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<!-- mybatis-flex -->
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot-starter</artifactId>
</dependency>
<!-- 自定义验证注解 --> <!-- 自定义验证注解 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -64,7 +47,7 @@
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</dependency> </dependency>
<!-- JSON工具类 --> <!-- JSON工具类 -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
@ -108,12 +91,6 @@
<version>2.3.1</version> <version>2.3.1</version>
</dependency> </dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 --> <!-- pool 对象池 -->
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
@ -132,6 +109,51 @@
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
</dependency> </dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-extra</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<scope>provided</scope>
</dependency>
<!-- mapstruct-plus -->
<dependency>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-spring-boot-starter</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,28 +0,0 @@
package com.ruoyi.common.core.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.core.enums.DataSourceType;
/**
* 自定义多数据源切换注解
*
* 优先级先方法后类如果方法覆盖了类上的数据源类型以方法的为准否则以类上的为准
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource
{
/**
* 切换数据源名称
*/
public DataSourceType value() default DataSourceType.MASTER;
}

View File

@ -1,51 +0,0 @@
package com.ruoyi.common.core.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.core.enums.BusinessType;
import com.ruoyi.common.core.enums.OperatorType;
/**
* 自定义操作日志记录注解
*
* @author ruoyi
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
/**
* 排除指定的请求参数
*/
public String[] excludeParamNames() default {};
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.core.config;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* 程序注解配置
*
* @author ruoyi
*/
@AutoConfiguration
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
public class ApplicationConfig
{
}

View File

@ -0,0 +1,48 @@
package com.ruoyi.common.core.config;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.Arrays;
import java.util.concurrent.Executor;
/**
* 异步配置
*
* @author Lion Li
*/
@EnableAsync(proxyTargetClass = true)
@AutoConfiguration
public class AsyncConfig implements AsyncConfigurer {
/**
* 自定义 @Async 注解使用系统线程池
*/
@Override
public Executor getAsyncExecutor() {
return SpringUtils.getBean("scheduledExecutorService");
}
/**
* 异步执行异常处理
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (throwable, method, objects) -> {
throwable.printStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("Exception message - ").append(throwable.getMessage())
.append(", Method name - ").append(method.getName());
if (ArrayUtil.isNotEmpty(objects)) {
sb.append(", Parameter value - ").append(Arrays.toString(objects));
}
throw new ServiceException(sb.toString());
};
}
}

View File

@ -1,76 +1,53 @@
package com.ruoyi.common.core.config; package com.ruoyi.common.core.config;
import lombok.Data;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* 读取项目相关配置 * 读取项目相关配置
* *
* @author ruoyi * @author ruoyi
*/ */
@Data
@Component @Component
@ConfigurationProperties(prefix = "ruoyi") @ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig public class RuoYiConfig {
{
/** 项目名称 */ /**
* 项目名称
*/
private String name; private String name;
/** 版本 */ /**
* 版本
*/
private String version; private String version;
/** 版权年份 */ /**
* 版权年份
*/
private String copyrightYear; private String copyrightYear;
/** 实例演示开关 */ /**
* 实例演示开关
*/
private boolean demoEnabled; private boolean demoEnabled;
/** 上传路径 */ /**
* 文件路径
*/
private static String profile; private static String profile;
/** 获取地址开关 */ /**
* 获取地址开关
*/
@Getter
private static boolean addressEnabled; private static boolean addressEnabled;
/** 验证码类型 */ public void setAddressEnabled(boolean addressEnabled) {
private static String captchaType; RuoYiConfig.addressEnabled = addressEnabled;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getCopyrightYear()
{
return copyrightYear;
}
public void setCopyrightYear(String copyrightYear)
{
this.copyrightYear = copyrightYear;
}
public boolean isDemoEnabled()
{
return demoEnabled;
}
public void setDemoEnabled(boolean demoEnabled)
{
this.demoEnabled = demoEnabled;
} }
public static String getProfile() public static String getProfile()
@ -78,29 +55,6 @@ public class RuoYiConfig
return profile; return profile;
} }
public void setProfile(String profile)
{
RuoYiConfig.profile = profile;
}
public static boolean isAddressEnabled()
{
return addressEnabled;
}
public void setAddressEnabled(boolean addressEnabled)
{
RuoYiConfig.addressEnabled = addressEnabled;
}
public static String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
RuoYiConfig.captchaType = captchaType;
}
/** /**
* 获取导入上传路径 * 获取导入上传路径
*/ */

View File

@ -0,0 +1,76 @@
package com.ruoyi.common.core.config;
import com.ruoyi.common.core.config.properties.ThreadPoolProperties;
import com.ruoyi.common.core.utils.Threads;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
*
* @author ruoyi
**/
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolConfig
{
/**
* 核心线程数 = cpu 核心数 + 1
*/
private final int core = Runtime.getRuntime().availableProcessors() + 1;
private ScheduledExecutorService scheduledExecutorService;
@Bean(name = "threadPoolTaskExecutor")
@ConditionalOnProperty(prefix = "thread-pool", name = "enabled", havingValue = "true")
public ThreadPoolTaskExecutor threadPoolTaskExecutor(ThreadPoolProperties threadPoolProperties) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(core);
executor.setMaxPoolSize(core * 2);
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(core,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
this.scheduledExecutorService = scheduledThreadPoolExecutor;
return scheduledThreadPoolExecutor;
}
/**
* 销毁事件
*/
@PreDestroy
public void destroy() {
try {
log.info("====关闭后台任务任务线程池====");
Threads.shutdownAndAwaitTermination(scheduledExecutorService);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,40 @@
package com.ruoyi.common.core.config;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.Properties;
/**
* 校验框架配置类
*
* @author Lion Li
*/
@AutoConfiguration
public class ValidatorConfig {
/**
* 配置校验框架 快速返回模式
*/
@Bean
public Validator validator(MessageSource messageSource) {
try (LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean()) {
// 国际化
factoryBean.setValidationMessageSource(messageSource);
// 设置使用 HibernateValidator 校验器
factoryBean.setProviderClass(HibernateValidator.class);
Properties properties = new Properties();
// 设置 快速异常返回
properties.setProperty("hibernate.validator.fail_fast", "true");
factoryBean.setValidationProperties(properties);
// 加载配置
factoryBean.afterPropertiesSet();
return factoryBean.getValidator();
}
}
}

View File

@ -0,0 +1,30 @@
package com.ruoyi.common.core.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 线程池 配置属性
*
* @author Lion Li
*/
@Data
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolProperties {
/**
* 是否开启线程池
*/
private boolean enabled;
/**
* 队列最大长度
*/
private int queueCapacity;
/**
* 线程池维护线程所允许的空闲时间
*/
private int keepAliveSeconds;
}

View File

@ -7,6 +7,11 @@ package com.ruoyi.common.core.constant;
*/ */
public class CacheConstants public class CacheConstants
{ {
/**
* 在线用户 redis key
*/
public static final String ONLINE_TOKEN_KEY = "online_tokens:";
/** /**
* 登录用户 redis key * 登录用户 redis key
*/ */

View File

@ -0,0 +1,63 @@
package com.ruoyi.common.core.constant;
/**
* 缓存组名称常量
* <p>
* key 格式为 cacheNames#ttl#maxIdleTime#maxSize
* <p>
* ttl 过期时间 如果设置为0则不过期 默认为0
* maxIdleTime 最大空闲时间 根据LRU算法清理空闲数据 如果设置为0则不检测 默认为0
* maxSize 组最大长度 根据LRU算法清理溢出数据 如果设置为0则无限长 默认为0
* <p>
* 例子: test#60stest#0#60stest#0#1m#1000test#1h#0#500
*
* @author Lion Li
*/
public interface CacheNames {
/**
* 演示案例
*/
String DEMO_CACHE = "demo:cache#60s#10m#20";
/**
* 系统配置
*/
String SYS_CONFIG = "sys_config";
/**
* 数据字典
*/
String SYS_DICT = "sys_dict";
/**
* 租户
*/
String SYS_TENANT = GlobalConstants.GLOBAL_REDIS_KEY + "sys_tenant#30d";
/**
* 用户账户
*/
String SYS_USER_NAME = "sys_user_name#30d";
/**
* 部门
*/
String SYS_DEPT = "sys_dept#30d";
/**
* OSS内容
*/
String SYS_OSS = "sys_oss#30d";
/**
* OSS配置
*/
String SYS_OSS_CONFIG = "sys_oss_config";
/**
* 在线用户
*/
String ONLINE_TOKEN = "online_tokens";
}

View File

@ -69,6 +69,11 @@ public class Constants
*/ */
public static final Integer CAPTCHA_EXPIRATION = 2; public static final Integer CAPTCHA_EXPIRATION = 2;
/**
* 登录用户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/** /**
* 令牌 * 令牌
*/ */

View File

@ -0,0 +1,39 @@
package com.ruoyi.common.core.constant;
/**
* 全局的key常量 (业务无关的key)
*
* @author Lion Li
*/
public interface GlobalConstants {
/**
* 全局 redis key (业务无关的key)
*/
String GLOBAL_REDIS_KEY = "global:";
/**
* 验证码 redis key
*/
String CAPTCHA_CODE_KEY = GLOBAL_REDIS_KEY + "captcha_codes:";
/**
* 防重提交 redis key
*/
String REPEAT_SUBMIT_KEY = GLOBAL_REDIS_KEY + "repeat_submit:";
/**
* 限流 redis key
*/
String RATE_LIMIT_KEY = GLOBAL_REDIS_KEY + "rate_limit:";
/**
* 登录账户密码错误次数 redis key
*/
String PWD_ERR_CNT_KEY = GLOBAL_REDIS_KEY + "pwd_err_cnt:";
/**
* 三方认证 redis key
*/
String SOCIAL_AUTH_CODE_KEY = GLOBAL_REDIS_KEY + "social_auth_codes:";
}

View File

@ -0,0 +1,45 @@
package com.ruoyi.common.core.constant;
/**
* 租户常量信息
*
* @author Lion Li
*/
public interface TenantConstants {
/**
* 租户正常状态
*/
String NORMAL = "0";
/**
* 租户封禁状态
*/
String DISABLE = "1";
/**
* 超级管理员ID
*/
Long SUPER_ADMIN_ID = 1L;
/**
* 超级管理员角色 roleKey
*/
String SUPER_ADMIN_ROLE_KEY = "superadmin";
/**
* 租户管理员角色 roleKey
*/
String TENANT_ADMIN_ROLE_KEY = "admin";
/**
* 租户管理员角色名称
*/
String TENANT_ADMIN_ROLE_NAME = "管理员";
/**
* 默认租户ID
*/
String DEFAULT_TENANT_ID = "000000";
}

View File

@ -2,65 +2,118 @@ package com.ruoyi.common.core.constant;
/** /**
* 用户常量信息 * 用户常量信息
* *
* @author ruoyi * @author ruoyi
*/ */
public class UserConstants public class UserConstants {
{
/** /**
* 平台内系统用户的唯一标志 * 平台内系统用户的唯一标志
*/ */
public static final String SYS_USER = "SYS_USER"; public static final String SYS_USER = "SYS_USER";
/** 正常状态 */ /**
* 正常状态
*/
public static final String NORMAL = "0"; public static final String NORMAL = "0";
/** 异常状态 */ /**
* 异常状态
*/
public static final String EXCEPTION = "1"; public static final String EXCEPTION = "1";
/** 用户封禁状态 */ /**
* 用户正常状态
*/
public static final String USER_NORMAL = "0";
/**
* 用户封禁状态
*/
public static final String USER_DISABLE = "1"; public static final String USER_DISABLE = "1";
/** 角色封禁状态 */ /**
* 角色正常状态
*/
public static final String ROLE_NORMAL = "0";
/**
* 角色封禁状态
*/
public static final String ROLE_DISABLE = "1"; public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */ /**
* 部门正常状态
*/
public static final String DEPT_NORMAL = "0"; public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */ /**
* 部门停用状态
*/
public static final String DEPT_DISABLE = "1"; public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */ /**
* 岗位正常状态
*/
public static final String POST_NORMAL = "0";
/**
* 岗位停用状态
*/
public static final String POST_DISABLE = "1";
/**
* 字典正常状态
*/
public static final String DICT_NORMAL = "0"; public static final String DICT_NORMAL = "0";
/** 是否为系统默认(是) */ /**
* 是否为系统默认
*/
public static final String YES = "Y"; public static final String YES = "Y";
/** 是否菜单外链(是) */ /**
* 是否菜单外链
*/
public static final String YES_FRAME = "0"; public static final String YES_FRAME = "0";
/** 是否菜单外链(否) */ /**
* 是否菜单外链
*/
public static final String NO_FRAME = "1"; public static final String NO_FRAME = "1";
/** 菜单类型(目录) */ /**
* 菜单类型目录
*/
public static final String TYPE_DIR = "M"; public static final String TYPE_DIR = "M";
/** 菜单类型(菜单) */ /**
* 菜单类型菜单
*/
public static final String TYPE_MENU = "C"; public static final String TYPE_MENU = "C";
/** 菜单类型(按钮) */ /**
* 菜单类型按钮
*/
public static final String TYPE_BUTTON = "F"; public static final String TYPE_BUTTON = "F";
/** Layout组件标识 */ /**
* Layout组件标识
*/
public final static String LAYOUT = "Layout"; public final static String LAYOUT = "Layout";
/** ParentView组件标识 */ /**
* ParentView组件标识
*/
public final static String PARENT_VIEW = "ParentView"; public final static String PARENT_VIEW = "ParentView";
/** InnerLink组件标识 */ /**
* InnerLink组件标识
*/
public final static String INNER_LINK = "InnerLink"; public final static String INNER_LINK = "InnerLink";
/** 校验是否唯一的返回标识 */ /**
* 校验是否唯一的返回标识
*/
public final static boolean UNIQUE = true; public final static boolean UNIQUE = true;
public final static boolean NOT_UNIQUE = false; public final static boolean NOT_UNIQUE = false;
@ -75,4 +128,9 @@ public class UserConstants
*/ */
public static final int PASSWORD_MIN_LENGTH = 5; public static final int PASSWORD_MIN_LENGTH = 5;
public static final int PASSWORD_MAX_LENGTH = 20; public static final int PASSWORD_MAX_LENGTH = 20;
/**
* 超级管理员ID
*/
public static final Long SUPER_ADMIN_ID = 1L;
} }

View File

@ -7,7 +7,7 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* 操作消息提醒 * 操作消息提醒
* *
* @author ruoyi * @author ruoyi
*/ */
public class AjaxResult extends HashMap<String, Object> public class AjaxResult extends HashMap<String, Object>
@ -32,7 +32,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 初始化一个新创建的 AjaxResult 对象 * 初始化一个新创建的 AjaxResult 对象
* *
* @param code 状态码 * @param code 状态码
* @param msg 返回内容 * @param msg 返回内容
*/ */
@ -44,7 +44,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 初始化一个新创建的 AjaxResult 对象 * 初始化一个新创建的 AjaxResult 对象
* *
* @param code 状态码 * @param code 状态码
* @param msg 返回内容 * @param msg 返回内容
* @param data 数据对象 * @param data 数据对象
@ -61,7 +61,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回成功消息 * 返回成功消息
* *
* @return 成功消息 * @return 成功消息
*/ */
public static AjaxResult success() public static AjaxResult success()
@ -71,7 +71,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回成功数据 * 返回成功数据
* *
* @return 成功消息 * @return 成功消息
*/ */
public static AjaxResult success(Object data) public static AjaxResult success(Object data)
@ -81,7 +81,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回成功消息 * 返回成功消息
* *
* @param msg 返回内容 * @param msg 返回内容
* @return 成功消息 * @return 成功消息
*/ */
@ -92,7 +92,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回成功消息 * 返回成功消息
* *
* @param msg 返回内容 * @param msg 返回内容
* @param data 数据对象 * @param data 数据对象
* @return 成功消息 * @return 成功消息
@ -127,7 +127,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回错误消息 * 返回错误消息
* *
* @return 错误消息 * @return 错误消息
*/ */
public static AjaxResult error() public static AjaxResult error()
@ -137,7 +137,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回错误消息 * 返回错误消息
* *
* @param msg 返回内容 * @param msg 返回内容
* @return 错误消息 * @return 错误消息
*/ */
@ -148,7 +148,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回错误消息 * 返回错误消息
* *
* @param msg 返回内容 * @param msg 返回内容
* @param data 数据对象 * @param data 数据对象
* @return 错误消息 * @return 错误消息
@ -160,7 +160,7 @@ public class AjaxResult extends HashMap<String, Object>
/** /**
* 返回错误消息 * 返回错误消息
* *
* @param code 状态码 * @param code 状态码
* @param msg 返回内容 * @param msg 返回内容
* @return 错误消息 * @return 错误消息

View File

@ -1,121 +0,0 @@
package com.ruoyi.common.core.core.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.mybatisflex.annotation.Column;
/**
* Entity基类
*
* @author ruoyi
*/
public class BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
/** 搜索值 */
@JsonIgnore
@Column(ignore = true)
private String searchValue;
/** 创建者 */
private String createBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** 更新者 */
private String updateBy;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** 备注 */
private String remark;
/** 请求参数 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Column(ignore = true)
private Map<String, Object> params;
public String getSearchValue()
{
return searchValue;
}
public void setSearchValue(String searchValue)
{
this.searchValue = searchValue;
}
public String getCreateBy()
{
return createBy;
}
public void setCreateBy(String createBy)
{
this.createBy = createBy;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public String getUpdateBy()
{
return updateBy;
}
public void setUpdateBy(String updateBy)
{
this.updateBy = updateBy;
}
public Date getUpdateTime()
{
return updateTime;
}
public void setUpdateTime(Date updateTime)
{
this.updateTime = updateTime;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params)
{
this.params = params;
}
}

View File

@ -1,15 +1,21 @@
package com.ruoyi.common.core.core.domain; package com.ruoyi.common.core.core.domain;
import java.io.Serial;
import java.io.Serializable; import java.io.Serializable;
import com.ruoyi.common.core.constant.HttpStatus; import com.ruoyi.common.core.constant.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;
/** /**
* 响应信息主体 * 响应信息主体
* *
* @author ruoyi * @author ruoyi
*/ */
@Data
@NoArgsConstructor
public class R<T> implements Serializable public class R<T> implements Serializable
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 成功 */ /** 成功 */
@ -34,6 +40,10 @@ public class R<T> implements Serializable
return restResult(data, SUCCESS, "操作成功"); return restResult(data, SUCCESS, "操作成功");
} }
public static <T> R<T> ok(String msg) {
return restResult(null, SUCCESS, msg);
}
public static <T> R<T> ok(T data, String msg) public static <T> R<T> ok(T data, String msg)
{ {
return restResult(data, SUCCESS, msg); return restResult(data, SUCCESS, msg);
@ -54,7 +64,7 @@ public class R<T> implements Serializable
return restResult(data, FAIL, "操作失败"); return restResult(data, FAIL, "操作失败");
} }
public static <T> R<T> fail(T data, String msg) public static <T> R<T> fail(String msg, T data)
{ {
return restResult(data, FAIL, msg); return restResult(data, FAIL, msg);
} }
@ -64,6 +74,27 @@ public class R<T> implements Serializable
return restResult(null, code, msg); return restResult(null, code, msg);
} }
/**
* 返回警告消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static <T> R<T> warn(String msg) {
return restResult(null, HttpStatus.WARN, msg);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static <T> R<T> warn(String msg, T data) {
return restResult(data, HttpStatus.WARN, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) private static <T> R<T> restResult(T data, int code, String msg)
{ {
R<T> apiResult = new R<>(); R<T> apiResult = new R<>();
@ -73,36 +104,6 @@ public class R<T> implements Serializable
return apiResult; return apiResult;
} }
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
public static <T> Boolean isError(R<T> ret) public static <T> Boolean isError(R<T> ret)
{ {
return !isSuccess(ret); return !isSuccess(ret);

View File

@ -0,0 +1,38 @@
package com.ruoyi.common.core.core.domain.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 角色
*
* @author Lion Li
*/
@Data
@NoArgsConstructor
public class RoleDTO implements Serializable {
/**
* 角色ID
*/
private Long roleId;
/**
* 角色名称
*/
private String roleName;
/**
* 角色权限
*/
private String roleKey;
/**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限
*/
private String dataScope;
}

View File

@ -0,0 +1,62 @@
package com.ruoyi.common.core.core.domain.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
/**
* 当前在线会话
*
* @author ruoyi
*/
@Data
@NoArgsConstructor
public class UserOnlineDTO implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 会话编号
*/
private String tokenId;
/**
* 部门名称
*/
private String deptName;
/**
* 用户名称
*/
private String userName;
/**
* 登录IP地址
*/
private String ipaddr;
/**
* 登录地址
*/
private String loginLocation;
/**
* 浏览器类型
*/
private String browser;
/**
* 操作系统
*/
private String os;
/**
* 登录时间
*/
private Long loginTime;
}

View File

@ -0,0 +1,35 @@
package com.ruoyi.common.core.core.domain.model;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 邮件登录对象
*
* @author Lion Li
*/
@Data
public class EmailLoginBody {
/**
* 租户ID
*/
@NotBlank(message = "{tenant.number.not.blank}")
private String tenantId;
/**
* 邮箱
*/
@NotBlank(message = "{user.email.not.blank}")
@Email(message = "{user.email.not.valid}")
private String email;
/**
* 邮箱code
*/
@NotBlank(message = "{email.code.not.blank}")
private String emailCode;
}

View File

@ -1,20 +1,60 @@
package com.ruoyi.common.core.core.domain.model; package com.ruoyi.common.core.core.domain.model;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.validate.auth.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
/** /**
* 用户登录对象 * 用户登录对象
* *
* @author ruoyi * @author ruoyi
*/ */
@Data
public class LoginBody public class LoginBody
{ {
/**
* 客户端id
*/
@NotBlank(message = "{auth.clientid.not.blank}")
private String clientId;
/**
* 客户端key
*/
private String clientKey;
/**
* 客户端秘钥
*/
private String clientSecret;
/**
* 授权类型
*/
@NotBlank(message = "{auth.grant.type.not.blank}")
private String grantType;
/**
* 租户ID
*/
//@NotBlank(message = "{tenant.number.not.blank}")
private Long tenantId;
/** /**
* 用户名 * 用户名
*/ */
@NotBlank(message = "{user.username.not.blank}", groups = {PasswordGroup.class})
@Length(min = UserConstants.USERNAME_MIN_LENGTH, max = UserConstants.USERNAME_MAX_LENGTH, message = "{user.username.length.valid}", groups = {PasswordGroup.class})
private String username; private String username;
/** /**
* 用户密码 * 用户密码
*/ */
@NotBlank(message = "{user.password.not.blank}", groups = {PasswordGroup.class})
@Length(min = UserConstants.PASSWORD_MIN_LENGTH, max = UserConstants.PASSWORD_MAX_LENGTH, message = "{user.password.length.valid}", groups = {PasswordGroup.class})
private String password; private String password;
/** /**
@ -27,43 +67,52 @@ public class LoginBody
*/ */
private String uuid; private String uuid;
public String getUsername() /**
{ * 手机号
return username; */
} @NotBlank(message = "{user.phonenumber.not.blank}", groups = {SmsGroup.class})
private String phonenumber;
public void setUsername(String username) /**
{ * 短信code
this.username = username; */
} @NotBlank(message = "{sms.code.not.blank}", groups = {SmsGroup.class})
private String smsCode;
public String getPassword() /**
{ * 邮箱
return password; */
} @NotBlank(message = "{user.email.not.blank}", groups = {EmailGroup.class})
@Email(message = "{user.email.not.valid}")
private String email;
public void setPassword(String password) /**
{ * 邮箱code
this.password = password; */
} @NotBlank(message = "{email.code.not.blank}", groups = {EmailGroup.class})
private String emailCode;
public String getCode() /**
{ * 小程序code
return code; */
} @NotBlank(message = "{xcx.code.not.blank}", groups = {WechatGroup.class})
private String xcxCode;
public void setCode(String code) /**
{ * 第三方登录平台
this.code = code; */
} @NotBlank(message = "{social.source.not.blank}" , groups = {SocialGroup.class})
private String source;
public String getUuid() /**
{ * 第三方登录code
return uuid; */
} @NotBlank(message = "{social.code.not.blank}" , groups = {SocialGroup.class})
private String socialCode;
public void setUuid(String uuid) /**
{ * 第三方登录socialState
this.uuid = uuid; */
} @NotBlank(message = "{social.state.not.blank}" , groups = {SocialGroup.class})
private String socialState;
} }

View File

@ -1,21 +1,30 @@
package com.ruoyi.common.core.core.domain.model; package com.ruoyi.common.core.core.domain.model;
import com.alibaba.fastjson2.annotation.JSONField; import com.ruoyi.common.core.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.core.domain.entity.SysUser; import lombok.Data;
import org.springframework.security.core.GrantedAuthority; import lombok.NoArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection; import java.util.List;
import java.util.Set; import java.util.Set;
import java.io.Serial;
/** /**
* 登录用户身份权限 * 登录用户身份权限
* *
* @author ruoyi * @author Lion Li
*/ */
public class LoginUser implements UserDetails @Data
@NoArgsConstructor
public class LoginUser
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/**
* 租户ID
*/
private Long tenantId;
/** /**
* 用户ID * 用户ID
*/ */
@ -26,11 +35,21 @@ public class LoginUser implements UserDetails
*/ */
private Long deptId; private Long deptId;
/**
* 部门名
*/
private String deptName;
/** /**
* 用户唯一标识 * 用户唯一标识
*/ */
private String token; private String token;
/**
* 用户类型
*/
private String userType;
/** /**
* 登录时间 * 登录时间
*/ */
@ -62,205 +81,47 @@ public class LoginUser implements UserDetails
private String os; private String os;
/** /**
* 权限列表 * 菜单权限
*/ */
private Set<String> permissions; private Set<String> menuPermission;
/** /**
* 用户信息 * 角色权限
*/ */
private SysUser user; private Set<String> rolePermission;
public LoginUser()
{
}
public LoginUser(SysUser user, Set<String> permissions)
{
this.user = user;
this.permissions = permissions;
}
public LoginUser(Long userId, Long deptId, SysUser user, Set<String> permissions)
{
this.userId = userId;
this.deptId = deptId;
this.user = user;
this.permissions = permissions;
}
public Long getUserId()
{
return userId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getDeptId()
{
return deptId;
}
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
public String getToken()
{
return token;
}
public void setToken(String token)
{
this.token = token;
}
@JSONField(serialize = false)
@Override
public String getPassword()
{
return user.getPassword();
}
@Override
public String getUsername()
{
return user.getUserName();
}
/** /**
* 账户是否未过期,过期无法验证 * 用户名
*/ */
@JSONField(serialize = false) private String username;
@Override
public boolean isAccountNonExpired()
{
return true;
}
/** /**
* 指定用户是否解锁,锁定的用户无法进行身份验证 * 用户昵称
*
* @return
*/ */
@JSONField(serialize = false) private String nickname;
@Override
public boolean isAccountNonLocked()
{
return true;
}
/** /**
* 指示是否已过期的用户的凭据(密码),过期的凭据防止认证 * 角色对象
*
* @return
*/ */
@JSONField(serialize = false) private List<RoleDTO> roles;
@Override
public boolean isCredentialsNonExpired()
{
return true;
}
/** /**
* 是否可用 ,禁用的用户不能身份验证 * 数据权限 当前角色ID
*
* @return
*/ */
@JSONField(serialize = false) private Long roleId;
@Override
public boolean isEnabled() /**
{ * 获取登录id
return true; */
public String getLoginId() {
if (userType == null) {
throw new IllegalArgumentException("用户类型不能为空");
}
if (userId == null) {
throw new IllegalArgumentException("用户ID不能为空");
}
return userType + ":" + userId;
} }
public Long getLoginTime()
{
return loginTime;
} }
public void setLoginTime(Long loginTime)
{
this.loginTime = loginTime;
}
public String getIpaddr()
{
return ipaddr;
}
public void setIpaddr(String ipaddr)
{
this.ipaddr = ipaddr;
}
public String getLoginLocation()
{
return loginLocation;
}
public void setLoginLocation(String loginLocation)
{
this.loginLocation = loginLocation;
}
public String getBrowser()
{
return browser;
}
public void setBrowser(String browser)
{
this.browser = browser;
}
public String getOs()
{
return os;
}
public void setOs(String os)
{
this.os = os;
}
public Long getExpireTime()
{
return expireTime;
}
public void setExpireTime(Long expireTime)
{
this.expireTime = expireTime;
}
public Set<String> getPermissions()
{
return permissions;
}
public void setPermissions(Set<String> permissions)
{
this.permissions = permissions;
}
public SysUser getUser()
{
return user;
}
public void setUser(SysUser user)
{
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
{
return null;
}
}

View File

@ -1,11 +1,16 @@
package com.ruoyi.common.core.core.domain.model; package com.ruoyi.common.core.core.domain.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
/** /**
* 用户注册对象 * 用户注册对象
* *
* @author ruoyi * @author ruoyi
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
public class RegisterBody extends LoginBody public class RegisterBody extends LoginBody
{ {
private String userType;
} }

View File

@ -4,7 +4,7 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* 分页数据 * 分页数据
* *
* @author ruoyi * @author ruoyi
*/ */
public class PageDomain public class PageDomain

View File

@ -1,15 +1,19 @@
package com.ruoyi.common.core.core.page; package com.ruoyi.common.core.core.page;
import cn.hutool.http.HttpStatus;
import java.io.Serial;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
* 表格分页数据对象 * 表格分页数据对象
* *
* @author ruoyi * @author ruoyi
*/ */
public class TableDataInfo implements Serializable public class TableDataInfo implements Serializable
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 总记录数 */ /** 总记录数 */
@ -33,7 +37,7 @@ public class TableDataInfo implements Serializable
/** /**
* 分页 * 分页
* *
* @param list 列表数据 * @param list 列表数据
* @param total 总记录数 * @param total 总记录数
*/ */
@ -43,6 +47,15 @@ public class TableDataInfo implements Serializable
this.total = total; this.total = total;
} }
public static TableDataInfo build(List<?> list) {
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.HTTP_OK);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(list.size());
return rspData;
}
public long getTotal() public long getTotal()
{ {
return total; return total;

View File

@ -5,7 +5,7 @@ import com.ruoyi.common.core.utils.ServletUtils;
/** /**
* 表格数据处理 * 表格数据处理
* *
* @author ruoyi * @author ruoyi
*/ */
public class TableSupport public class TableSupport

View File

@ -1,268 +0,0 @@
package com.ruoyi.common.core.core.redis;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* spring redis 工具类
*
* @author ruoyi
**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
@Autowired
public RedisTemplate redisTemplate;
/**
* 缓存基本的对象IntegerString实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
*/
public <T> void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
/**
* 缓存基本的对象IntegerString实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @return true=设置成功false=设置失败
*/
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @param unit 时间单位
* @return true=设置成功false=设置失败
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
/**
* 获取有效时间
*
* @param key Redis键
* @return 有效时间
*/
public long getExpire(final String key)
{
return redisTemplate.getExpire(key);
}
/**
* 判断 key是否存在
*
* @param key
* @return true 存在 false不存在
*/
public Boolean hasKey(String key)
{
return redisTemplate.hasKey(key);
}
/**
* 获得缓存的基本对象
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(final String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 删除单个对象
*
* @param key
*/
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
/**
* 删除集合对象
*
* @param collection 多个对象
* @return
*/
public boolean deleteObject(final Collection collection)
{
return redisTemplate.delete(collection) > 0;
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public <T> long setCacheList(final String key, final List<T> dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
/**
* 缓存Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入数据
*
* @param key Redis键
* @param hKey Hash键
* @param value
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* 获取Hash中的数据
*
* @param key Redis键
* @param hKey Hash键
* @return Hash中的对象
*/
public <T> T getCacheMapValue(final String key, final String hKey)
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hKeys Hash键集合
* @return Hash对象集合
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* 删除Hash中的某条数据
*
* @param key Redis键
* @param hKey Hash键
* @return 是否成功
*/
public boolean deleteCacheMapValue(final String key, final String hKey)
{
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public Collection<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
}

View File

@ -6,7 +6,7 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* 字符集工具类 * 字符集工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class CharsetKit public class CharsetKit
@ -27,7 +27,7 @@ public class CharsetKit
/** /**
* 转换为Charset对象 * 转换为Charset对象
* *
* @param charset 字符集为空则返回默认字符集 * @param charset 字符集为空则返回默认字符集
* @return Charset * @return Charset
*/ */
@ -38,7 +38,7 @@ public class CharsetKit
/** /**
* 转换字符串的字符集编码 * 转换字符串的字符集编码
* *
* @param source 字符串 * @param source 字符串
* @param srcCharset 源字符集默认ISO-8859-1 * @param srcCharset 源字符集默认ISO-8859-1
* @param destCharset 目标字符集默认UTF-8 * @param destCharset 目标字符集默认UTF-8
@ -51,7 +51,7 @@ public class CharsetKit
/** /**
* 转换字符串的字符集编码 * 转换字符串的字符集编码
* *
* @param source 字符串 * @param source 字符串
* @param srcCharset 源字符集默认ISO-8859-1 * @param srcCharset 源字符集默认ISO-8859-1
* @param destCharset 目标字符集默认UTF-8 * @param destCharset 目标字符集默认UTF-8

View File

@ -4,7 +4,7 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* 字符串格式化 * 字符串格式化
* *
* @author ruoyi * @author ruoyi
*/ */
public class StrFormatter public class StrFormatter
@ -22,7 +22,7 @@ public class StrFormatter
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br> * 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br> * 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
* *
* @param strPattern 字符串模板 * @param strPattern 字符串模板
* @param argArray 参数列表 * @param argArray 参数列表
* @return 结果 * @return 结果

View File

@ -1,19 +0,0 @@
package com.ruoyi.common.core.enums;
/**
* 数据源
*
* @author ruoyi
*/
public enum DataSourceType
{
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE
}

View File

@ -0,0 +1,35 @@
package com.ruoyi.common.core.enums;
/**
* 设备类型
* 针对一套 用户体系
*
* @author Lion Li
*/
public enum DeviceType {
/**
* pc端
*/
PC("pc"),
/**
* app端
*/
APP("app"),
/**
* 小程序端
*/
XCX("xcx"),
/**
* social第三方端
*/
SOCIAL("social");
private final String device;
private DeviceType(String device) {
this.device = device;
}
}

View File

@ -0,0 +1,44 @@
package com.ruoyi.common.core.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 登录类型
*
* @author Lion Li
*/
@Getter
@AllArgsConstructor
public enum LoginType {
/**
* 密码登录
*/
PASSWORD("user.password.retry.limit.exceed", "user.password.retry.limit.count"),
/**
* 短信登录
*/
SMS("sms.code.retry.limit.exceed", "sms.code.retry.limit.count"),
/**
* 邮箱登录
*/
EMAIL("email.code.retry.limit.exceed", "email.code.retry.limit.count"),
/**
* 小程序登录
*/
XCX("", "");
/**
* 登录重试超出限制提示
*/
final String retryLimitExceed;
/**
* 登录重试限制计数提示
*/
final String retryLimitCount;
}

View File

@ -0,0 +1,41 @@
package com.ruoyi.common.core.enums;
import com.ruoyi.common.core.utils.StringUtils;
/**
* 设备类型
* 针对多套 用户体系
*
* @author Lion Li
*/
public enum UserType {
/**
* pc端
*/
SYS_USER("sys_user"),
/**
* app端
*/
APP_USER("app_user");
private final String userType;
UserType(String userType) {
this.userType = userType;
}
public String getUserType() {
return userType;
}
public static UserType getUserType(String str) {
for (UserType value : values()) {
if (StringUtils.contains(str, value.getUserType())) {
return value;
}
}
throw new RuntimeException("'UserType' not found By " + str);
}
}

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception; package com.ruoyi.common.core.exception;
import java.io.Serial;
/** /**
* 全局异常 * 全局异常
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception;
*/ */
public class GlobalException extends RuntimeException public class GlobalException extends RuntimeException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -17,7 +20,6 @@ public class GlobalException extends RuntimeException
/** /**
* 错误明细内部调试错误 * 错误明细内部调试错误
* *
* {@link CommonResult#getDetailMessage()} 一致的设计
*/ */
private String detailMessage; private String detailMessage;

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception; package com.ruoyi.common.core.exception;
import java.io.Serial;
/** /**
* 业务异常 * 业务异常
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception;
*/ */
public final class ServiceException extends RuntimeException public final class ServiceException extends RuntimeException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -22,7 +25,6 @@ public final class ServiceException extends RuntimeException
/** /**
* 错误明细内部调试错误 * 错误明细内部调试错误
* *
* {@link CommonResult#getDetailMessage()} 一致的设计
*/ */
private String detailMessage; private String detailMessage;

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception; package com.ruoyi.common.core.exception;
import java.io.Serial;
/** /**
* 工具类异常 * 工具类异常
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception;
*/ */
public class UtilException extends RuntimeException public class UtilException extends RuntimeException
{ {
@Serial
private static final long serialVersionUID = 8247610319171014183L; private static final long serialVersionUID = 8247610319171014183L;
public UtilException(Throwable e) public UtilException(Throwable e)

View File

@ -3,6 +3,8 @@ package com.ruoyi.common.core.exception.base;
import com.ruoyi.common.core.utils.MessageUtils; import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import java.io.Serial;
/** /**
* 基础异常 * 基础异常
* *
@ -10,6 +12,7 @@ import com.ruoyi.common.core.utils.StringUtils;
*/ */
public class BaseException extends RuntimeException public class BaseException extends RuntimeException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**

View File

@ -2,6 +2,8 @@ package com.ruoyi.common.core.exception.file;
import com.ruoyi.common.core.exception.base.BaseException; import com.ruoyi.common.core.exception.base.BaseException;
import java.io.Serial;
/** /**
* 文件信息异常类 * 文件信息异常类
* *
@ -9,6 +11,7 @@ import com.ruoyi.common.core.exception.base.BaseException;
*/ */
public class FileException extends BaseException public class FileException extends BaseException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileException(String code, Object[] args) public FileException(String code, Object[] args)

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.file; package com.ruoyi.common.core.exception.file;
import java.io.Serial;
/** /**
* 文件名称超长限制异常类 * 文件名称超长限制异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.file;
*/ */
public class FileNameLengthLimitExceededException extends FileException public class FileNameLengthLimitExceededException extends FileException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileNameLengthLimitExceededException(int defaultFileNameLength) public FileNameLengthLimitExceededException(int defaultFileNameLength)

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.file; package com.ruoyi.common.core.exception.file;
import java.io.Serial;
/** /**
* 文件名大小限制异常类 * 文件名大小限制异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.file;
*/ */
public class FileSizeLimitExceededException extends FileException public class FileSizeLimitExceededException extends FileException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileSizeLimitExceededException(long defaultMaxSize) public FileSizeLimitExceededException(long defaultMaxSize)

View File

@ -2,6 +2,7 @@ package com.ruoyi.common.core.exception.file;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.Serial;
/** /**
* 文件上传异常类 * 文件上传异常类
@ -10,7 +11,7 @@ import java.io.PrintWriter;
*/ */
public class FileUploadException extends Exception public class FileUploadException extends Exception
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final Throwable cause; private final Throwable cause;

View File

@ -1,5 +1,6 @@
package com.ruoyi.common.core.exception.file; package com.ruoyi.common.core.exception.file;
import java.io.Serial;
import java.util.Arrays; import java.util.Arrays;
/** /**
@ -9,6 +10,7 @@ import java.util.Arrays;
*/ */
public class InvalidExtensionException extends FileUploadException public class InvalidExtensionException extends FileUploadException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String[] allowedExtension; private String[] allowedExtension;

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.job; package com.ruoyi.common.core.exception.job;
import java.io.Serial;
/** /**
* 计划策略异常 * 计划策略异常
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.job;
*/ */
public class TaskException extends Exception public class TaskException extends Exception
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Code code; private Code code;

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 黑名单IP异常类 * 黑名单IP异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class BlackListException extends UserException public class BlackListException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public BlackListException() public BlackListException()

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 验证码错误异常类 * 验证码错误异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class CaptchaException extends UserException public class CaptchaException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CaptchaException() public CaptchaException()

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 验证码失效异常类 * 验证码失效异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class CaptchaExpireException extends UserException public class CaptchaExpireException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CaptchaExpireException() public CaptchaExpireException()

View File

@ -2,16 +2,19 @@ package com.ruoyi.common.core.exception.user;
import com.ruoyi.common.core.exception.base.BaseException; import com.ruoyi.common.core.exception.base.BaseException;
import java.io.Serial;
/** /**
* 用户信息异常类 * 用户信息异常类
* *
* @author ruoyi * @author ruoyi
*/ */
public class UserException extends BaseException public class UserException extends BaseException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserException(String code, Object[] args) public UserException(String code, Object... args)
{ {
super("user", code, args, null); super("user", code, args, null);
} }

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 用户不存在异常类 * 用户不存在异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class UserNotExistsException extends UserException public class UserNotExistsException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserNotExistsException() public UserNotExistsException()

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 用户密码不正确或不符合规范异常类 * 用户密码不正确或不符合规范异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class UserPasswordNotMatchException extends UserException public class UserPasswordNotMatchException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserPasswordNotMatchException() public UserPasswordNotMatchException()

View File

@ -1,5 +1,7 @@
package com.ruoyi.common.core.exception.user; package com.ruoyi.common.core.exception.user;
import java.io.Serial;
/** /**
* 用户错误最大次数异常类 * 用户错误最大次数异常类
* *
@ -7,6 +9,7 @@ package com.ruoyi.common.core.exception.user;
*/ */
public class UserPasswordRetryLimitExceedException extends UserException public class UserPasswordRetryLimitExceedException extends UserException
{ {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserPasswordRetryLimitExceedException(int retryLimitCount, int lockTime) public UserPasswordRetryLimitExceedException(int retryLimitCount, int lockTime)

View File

@ -0,0 +1,31 @@
package com.ruoyi.common.core.factory;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
/**
* yml 配置源工厂
*
* @author Lion Li
*/
public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = resource.getResource().getFilename();
if (StringUtils.isNotBlank(sourceName) && StringUtils.endsWithAny(sourceName, ".yml", ".yaml")) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return new PropertiesPropertySource(sourceName, factory.getObject());
}
return super.createPropertySource(name, resource);
}
}

View File

@ -1,24 +0,0 @@
package com.ruoyi.common.core.filter;
import com.alibaba.fastjson2.filter.SimplePropertyPreFilter;
/**
* 排除JSON敏感属性
*
* @author ruoyi
*/
public class PropertyPreExcludeFilter extends SimplePropertyPreFilter
{
public PropertyPreExcludeFilter()
{
}
public PropertyPreExcludeFilter addExcludes(String... filters)
{
for (int i = 0; i < filters.length; i++)
{
this.getExcludes().add(filters[i]);
}
return this;
}
}

View File

@ -0,0 +1,41 @@
package com.ruoyi.common.core.manager;
import com.ruoyi.common.core.utils.Threads;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.ScheduledExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 确保应用退出时能关闭后台线程
*
* @author ruoyi
*/
@Component
public class ShutdownManager
{
private static final Logger logger = LoggerFactory.getLogger("ShutdownManager");
@Resource
@Qualifier("scheduledExecutorService")
private ScheduledExecutorService scheduledExecutorService;
@PreDestroy
public void destroy() {
shutdownAsyncManager();
}
/**
* 停止异步执行任务
*/
private void shutdownAsyncManager() {
try {
logger.info("====关闭后台任务任务线程池====");
Threads.shutdownAndAwaitTermination(scheduledExecutorService);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.core.service;
/**
* 通用 参数配置服务
*
* @author Lion Li
*/
public interface ConfigService {
/**
* 根据参数 key 获取参数值
*
* @param configKey 参数 key
* @return 参数值
*/
String getConfigValue(String configKey);
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.core.service;
/**
* 通用 部门服务
*
* @author Lion Li
*/
public interface DeptService {
/**
* 通过部门ID查询部门名称
*
* @param deptIds 部门ID串逗号分隔
* @return 部门名称串逗号分隔
*/
String selectDeptNameByIds(String deptIds);
}

View File

@ -0,0 +1,67 @@
package com.ruoyi.common.core.service;
import java.util.Map;
/**
* 通用 字典服务
*
* @author Lion Li
*/
public interface DictService {
/**
* 分隔符
*/
String SEPARATOR = ",";
/**
* 根据字典类型和字典值获取字典标签
*
* @param dictType 字典类型
* @param dictValue 字典值
* @return 字典标签
*/
default String getDictLabel(String dictType, String dictValue) {
return getDictLabel(dictType, dictValue, SEPARATOR);
}
/**
* 根据字典类型和字典标签获取字典值
*
* @param dictType 字典类型
* @param dictLabel 字典标签
* @return 字典值
*/
default String getDictValue(String dictType, String dictLabel) {
return getDictValue(dictType, dictLabel, SEPARATOR);
}
/**
* 根据字典类型和字典值获取字典标签
*
* @param dictType 字典类型
* @param dictValue 字典值
* @param separator 分隔符
* @return 字典标签
*/
String getDictLabel(String dictType, String dictValue, String separator);
/**
* 根据字典类型和字典标签获取字典值
*
* @param dictType 字典类型
* @param dictLabel 字典标签
* @param separator 分隔符
* @return 字典值
*/
String getDictValue(String dictType, String dictLabel, String separator);
/**
* 获取字典下所有的字典值与标签
*
* @param dictType 字典类型
* @return dictValue为keydictLabel为值组成的Map
*/
Map<String, String> getAllDictByDictType(String dictType);
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.core.service;
/**
* 通用 用户服务
*
* @author Lion Li
*/
public interface UserService {
/**
* 通过用户ID查询用户账户
*
* @param userId 用户ID
* @return 用户账户
*/
String selectUserNameById(Long userId);
}

View File

@ -1,186 +0,0 @@
package com.ruoyi.common.core.utils;
import java.util.Collection;
import java.util.List;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.core.domain.entity.SysDictData;
import com.ruoyi.common.core.core.redis.RedisCache;
import com.ruoyi.common.core.utils.spring.SpringUtils;
/**
* 字典工具类
*
* @author ruoyi
*/
public class DictUtils
{
/**
* 分隔符
*/
public static final String SEPARATOR = ",";
/**
* 设置字典缓存
*
* @param key 参数键
* @param dictDatas 字典数据列表
*/
public static void setDictCache(String key, List<SysDictData> dictDatas)
{
SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
}
/**
* 获取字典缓存
*
* @param key 参数键
* @return dictDatas 字典数据列表
*/
public static List<SysDictData> getDictCache(String key)
{
JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
if (StringUtils.isNotNull(arrayCache))
{
return arrayCache.toList(SysDictData.class);
}
return null;
}
/**
* 根据字典类型和字典值获取字典标签
*
* @param dictType 字典类型
* @param dictValue 字典值
* @return 字典标签
*/
public static String getDictLabel(String dictType, String dictValue)
{
return getDictLabel(dictType, dictValue, SEPARATOR);
}
/**
* 根据字典类型和字典标签获取字典值
*
* @param dictType 字典类型
* @param dictLabel 字典标签
* @return 字典值
*/
public static String getDictValue(String dictType, String dictLabel)
{
return getDictValue(dictType, dictLabel, SEPARATOR);
}
/**
* 根据字典类型和字典值获取字典标签
*
* @param dictType 字典类型
* @param dictValue 字典值
* @param separator 分隔符
* @return 字典标签
*/
public static String getDictLabel(String dictType, String dictValue, String separator)
{
StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.isNotNull(datas))
{
if (StringUtils.containsAny(separator, dictValue))
{
for (SysDictData dict : datas)
{
for (String value : dictValue.split(separator))
{
if (value.equals(dict.getDictValue()))
{
propertyString.append(dict.getDictLabel()).append(separator);
break;
}
}
}
}
else
{
for (SysDictData dict : datas)
{
if (dictValue.equals(dict.getDictValue()))
{
return dict.getDictLabel();
}
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
/**
* 根据字典类型和字典标签获取字典值
*
* @param dictType 字典类型
* @param dictLabel 字典标签
* @param separator 分隔符
* @return 字典值
*/
public static String getDictValue(String dictType, String dictLabel, String separator)
{
StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas))
{
for (SysDictData dict : datas)
{
for (String label : dictLabel.split(separator))
{
if (label.equals(dict.getDictLabel()))
{
propertyString.append(dict.getDictValue()).append(separator);
break;
}
}
}
}
else
{
for (SysDictData dict : datas)
{
if (dictLabel.equals(dict.getDictLabel()))
{
return dict.getDictValue();
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
/**
* 删除指定字典缓存
*
* @param key 字典键
*/
public static void removeDictCache(String key)
{
SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
}
/**
* 清空字典缓存
*/
public static void clearDictCache()
{
Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*");
SpringUtils.getBean(RedisCache.class).deleteObject(keys);
}
/**
* 设置cache key
*
* @param configKey 参数键
* @return 缓存键key
*/
public static String getCacheKey(String configKey)
{
return CacheConstants.SYS_DICT_KEY + configKey;
}
}

View File

@ -1,18 +0,0 @@
package com.ruoyi.common.core.utils;
/**
* 处理并记录日志文件
*
* @author ruoyi
*/
public class LogUtils
{
public static String getBlock(Object msg)
{
if (msg == null)
{
msg = "";
}
return "[" + msg.toString() + "]";
}
}

View File

@ -0,0 +1,93 @@
package com.ruoyi.common.core.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import io.github.linpeilie.Converter;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* Mapstruct 工具类
* <p>参考文档<a href="https://mapstruct.plus/introduction/quick-start.html">mapstruct-plus</a></p>
*
*
* @author Michelle.Chung
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MapstructUtils {
private final static Converter CONVERTER = SpringUtils.getBean(Converter.class);
/**
* T 类型对象转换为 desc 类型的对象并返回
*
* @param source 数据来源实体
* @param desc 描述对象 转换后的对象
* @return desc
*/
public static <T, V> V convert(T source, Class<V> desc) {
if (ObjectUtil.isNull(source)) {
return null;
}
if (ObjectUtil.isNull(desc)) {
return null;
}
return CONVERTER.convert(source, desc);
}
/**
* T 类型对象按照配置的映射字段规则 desc 类型的对象赋值并返回 desc 对象
*
* @param source 数据来源实体
* @param desc 转换后的对象
* @return desc
*/
public static <T, V> V convert(T source, V desc) {
if (ObjectUtil.isNull(source)) {
return null;
}
if (ObjectUtil.isNull(desc)) {
return null;
}
return CONVERTER.convert(source, desc);
}
/**
* T 类型的集合转换为 desc 类型的集合并返回
*
* @param sourceList 数据来源实体列表
* @param desc 描述对象 转换后的对象
* @return desc
*/
public static <T, V> List<V> convert(List<T> sourceList, Class<V> desc) {
if (ObjectUtil.isNull(sourceList)) {
return null;
}
if (CollUtil.isEmpty(sourceList)) {
return CollUtil.newArrayList();
}
return CONVERTER.convert(sourceList, desc);
}
/**
* Map 转换为 beanClass 类型的集合并返回
*
* @param map 数据来源
* @param beanClass bean类
* @return bean对象
*/
public static <T> T convert(Map<String, Object> map, Class<T> beanClass) {
if (MapUtil.isEmpty(map)) {
return null;
}
if (ObjectUtil.isNull(beanClass)) {
return null;
}
return CONVERTER.convert(map, beanClass);
}
}

View File

@ -2,11 +2,10 @@ package com.ruoyi.common.core.utils;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
import com.ruoyi.common.core.utils.spring.SpringUtils;
/** /**
* 获取i18n资源文件 * 获取i18n资源文件
* *
* @author ruoyi * @author ruoyi
*/ */
public class MessageUtils public class MessageUtils

View File

@ -7,7 +7,7 @@ import com.ruoyi.common.core.utils.sql.SqlUtil;
/** /**
* 分页工具类 * 分页工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class PageUtils extends PageHelper public class PageUtils extends PageHelper

View File

@ -1,120 +0,0 @@
package com.ruoyi.common.core.utils;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.exception.ServiceException;
/**
* 安全服务工具类
*
* @author ruoyi
*/
public class SecurityUtils
{
/**
* 用户ID
**/
public static Long getUserId()
{
try
{
return getLoginUser().getUserId();
}
catch (Exception e)
{
throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取部门ID
**/
public static Long getDeptId()
{
try
{
return getLoginUser().getDeptId();
}
catch (Exception e)
{
throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户账户
**/
public static String getUsername()
{
try
{
return getLoginUser().getUsername();
}
catch (Exception e)
{
throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户
**/
public static LoginUser getLoginUser()
{
try
{
return (LoginUser) getAuthentication().getPrincipal();
}
catch (Exception e)
{
throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取Authentication
*/
public static Authentication getAuthentication()
{
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
/**
* 判断密码是否相同
*
* @param rawPassword 真实密码
* @param encodedPassword 加密后字符
* @return 结果
*/
public static boolean matchesPassword(String rawPassword, String encodedPassword)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
/**
* 是否为管理员
*
* @param userId 用户ID
* @return 结果
*/
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
}

View File

@ -17,13 +17,14 @@ import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import com.ruoyi.common.core.constant.Constants; import com.ruoyi.common.core.constant.Constants;
import cn.hutool.extra.servlet.JakartaServletUtil;
/** /**
* 客户端工具类 * 客户端工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class ServletUtils public class ServletUtils extends JakartaServletUtil
{ {
/** /**
* 获取String参数 * 获取String参数
@ -133,7 +134,7 @@ public class ServletUtils
/** /**
* 将字符串渲染到客户端 * 将字符串渲染到客户端
* *
* @param response 渲染对象 * @param response 渲染对象
* @param string 待渲染的字符串 * @param string 待渲染的字符串
*/ */
@ -154,7 +155,7 @@ public class ServletUtils
/** /**
* 是否是Ajax异步请求 * 是否是Ajax异步请求
* *
* @param request * @param request
*/ */
public static boolean isAjaxRequest(HttpServletRequest request) public static boolean isAjaxRequest(HttpServletRequest request)
@ -181,9 +182,13 @@ public class ServletUtils
return StringUtils.inStringIgnoreCase(ajax, "json", "xml"); return StringUtils.inStringIgnoreCase(ajax, "json", "xml");
} }
public static String getClientIP() {
return getClientIP(getRequest());
}
/** /**
* 内容编码 * 内容编码
* *
* @param str 内容 * @param str 内容
* @return 编码后的内容 * @return 编码后的内容
*/ */
@ -201,7 +206,7 @@ public class ServletUtils
/** /**
* 内容解码 * 内容解码
* *
* @param str 内容 * @param str 内容
* @return 解码后的内容 * @return 解码后的内容
*/ */

View File

@ -0,0 +1,101 @@
package com.ruoyi.common.core.utils;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* spring工具类方便在非spring管理环境中获取bean
*
* @author ruoyi
*/
@Component
public final class SpringUtils extends SpringUtil
{
/**
* 获取spring上下文
*/
public static ApplicationContext context() {
return getApplicationContext();
}
/**
* 获取aop代理对象
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker) {
return (T) AopContext.currentProxy();
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return getBeanFactory().containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype 如果与给定名字相应的bean定义没有被找到将会抛出一个异常NoSuchBeanDefinitionException
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return getBeanFactory().isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return getBeanFactory().getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return getBeanFactory().getAliases(name);
}
/**
* 获取当前的环境配置无配置返回null
*
* @return 当前的环境配置
*/
public static String[] getActiveProfiles()
{
return context().getEnvironment().getActiveProfiles();
}
/**
* 获取当前的环境配置当有多个环境配置时只获取第一个
*
* @return 当前的环境配置
*/
public static String getActiveProfile()
{
final String[] activeProfiles = getActiveProfiles();
return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
}

View File

@ -0,0 +1,254 @@
package com.ruoyi.common.core.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* stream 流工具类
*
* @author Lion Li
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtils {
/**
* 将collection过滤
*
* @param collection 需要转化的集合
* @param function 过滤方法
* @return 过滤后的list
*/
public static <E> List<E> filter(Collection<E> collection, Predicate<E> function) {
if (CollUtil.isEmpty(collection)) {
return CollUtil.newArrayList();
}
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
return collection.stream().filter(function).collect(Collectors.toList());
}
/**
* 将collection拼接
*
* @param collection 需要转化的集合
* @param function 拼接方法
* @return 拼接后的list
*/
public static <E> String join(Collection<E> collection, Function<E, String> function) {
return join(collection, function, StringUtils.SEPARATOR);
}
/**
* 将collection拼接
*
* @param collection 需要转化的集合
* @param function 拼接方法
* @param delimiter 拼接符
* @return 拼接后的list
*/
public static <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) {
if (CollUtil.isEmpty(collection)) {
return StringUtils.EMPTY;
}
return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
}
/**
* 将collection排序
*
* @param collection 需要转化的集合
* @param comparing 排序方法
* @return 排序后的list
*/
public static <E> List<E> sorted(Collection<E> collection, Comparator<E> comparing) {
if (CollUtil.isEmpty(collection)) {
return CollUtil.newArrayList();
}
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
return collection.stream().filter(Objects::nonNull).sorted(comparing).collect(Collectors.toList());
}
/**
* 将collection转化为类型不变的map<br>
* <B>{@code Collection<V> ----> Map<K,V>}</B>
*
* @param collection 需要转化的集合
* @param key V类型转化为K类型的lambda方法
* @param <V> collection中的泛型
* @param <K> map中的key类型
* @return 转化后的map
*/
public static <V, K> Map<K, V> toIdentityMap(Collection<V> collection, Function<V, K> key) {
if (CollUtil.isEmpty(collection)) {
return MapUtil.newHashMap();
}
return collection.stream().filter(Objects::nonNull).collect(Collectors.toMap(key, Function.identity(), (l, r) -> l));
}
/**
* 将Collection转化为map(value类型与collection的泛型不同)<br>
* <B>{@code Collection<E> -----> Map<K,V> }</B>
*
* @param collection 需要转化的集合
* @param key E类型转化为K类型的lambda方法
* @param value E类型转化为V类型的lambda方法
* @param <E> collection中的泛型
* @param <K> map中的key类型
* @param <V> map中的value类型
* @return 转化后的map
*/
public static <E, K, V> Map<K, V> toMap(Collection<E> collection, Function<E, K> key, Function<E, V> value) {
if (CollUtil.isEmpty(collection)) {
return MapUtil.newHashMap();
}
return collection.stream().filter(Objects::nonNull).collect(Collectors.toMap(key, value, (l, r) -> l));
}
/**
* 将collection按照规则(比如有相同的班级id)分类成map<br>
* <B>{@code Collection<E> -------> Map<K,List<E>> } </B>
*
* @param collection 需要分类的集合
* @param key 分类的规则
* @param <E> collection中的泛型
* @param <K> map中的key类型
* @return 分类后的map
*/
public static <E, K> Map<K, List<E>> groupByKey(Collection<E> collection, Function<E, K> key) {
if (CollUtil.isEmpty(collection)) {
return MapUtil.newHashMap();
}
return collection
.stream().filter(Objects::nonNull)
.collect(Collectors.groupingBy(key, LinkedHashMap::new, Collectors.toList()));
}
/**
* 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br>
* <B>{@code Collection<E> ---> Map<T,Map<U,List<E>>> } </B>
*
* @param collection 需要分类的集合
* @param key1 第一个分类的规则
* @param key2 第二个分类的规则
* @param <E> 集合元素类型
* @param <K> 第一个map中的key类型
* @param <U> 第二个map中的key类型
* @return 分类后的map
*/
public static <E, K, U> Map<K, Map<U, List<E>>> groupBy2Key(Collection<E> collection, Function<E, K> key1, Function<E, U> key2) {
if (CollUtil.isEmpty(collection)) {
return MapUtil.newHashMap();
}
return collection
.stream().filter(Objects::nonNull)
.collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.groupingBy(key2, LinkedHashMap::new, Collectors.toList())));
}
/**
* 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br>
* <B>{@code Collection<E> ---> Map<T,Map<U,E>> } </B>
*
* @param collection 需要分类的集合
* @param key1 第一个分类的规则
* @param key2 第二个分类的规则
* @param <T> 第一个map中的key类型
* @param <U> 第二个map中的key类型
* @param <E> collection中的泛型
* @return 分类后的map
*/
public static <E, T, U> Map<T, Map<U, E>> group2Map(Collection<E> collection, Function<E, T> key1, Function<E, U> key2) {
if (CollUtil.isEmpty(collection) || key1 == null || key2 == null) {
return MapUtil.newHashMap();
}
return collection
.stream().filter(Objects::nonNull)
.collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.toMap(key2, Function.identity(), (l, r) -> l)));
}
/**
* 将collection转化为List集合但是两者的泛型不同<br>
* <B>{@code Collection<E> ------> List<T> } </B>
*
* @param collection 需要转化的集合
* @param function collection中的泛型转化为list泛型的lambda表达式
* @param <E> collection中的泛型
* @param <T> List中的泛型
* @return 转化后的list
*/
public static <E, T> List<T> toList(Collection<E> collection, Function<E, T> function) {
if (CollUtil.isEmpty(collection)) {
return CollUtil.newArrayList();
}
return collection
.stream()
.map(function)
.filter(Objects::nonNull)
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
.collect(Collectors.toList());
}
/**
* 将collection转化为Set集合但是两者的泛型不同<br>
* <B>{@code Collection<E> ------> Set<T> } </B>
*
* @param collection 需要转化的集合
* @param function collection中的泛型转化为set泛型的lambda表达式
* @param <E> collection中的泛型
* @param <T> Set中的泛型
* @return 转化后的Set
*/
public static <E, T> Set<T> toSet(Collection<E> collection, Function<E, T> function) {
if (CollUtil.isEmpty(collection) || function == null) {
return CollUtil.newHashSet();
}
return collection
.stream()
.map(function)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
/**
* 合并两个相同key类型的map
*
* @param map1 第一个需要合并的 map
* @param map2 第二个需要合并的 map
* @param merge 合并的lambda将key value1 value2合并成最终的类型,注意value可能为空的情况
* @param <K> map中的key类型
* @param <X> 第一个 map的value类型
* @param <Y> 第二个 map的value类型
* @param <V> 最终map的value类型
* @return 合并后的map
*/
public static <K, X, Y, V> Map<K, V> merge(Map<K, X> map1, Map<K, Y> map2, BiFunction<X, Y, V> merge) {
if (MapUtil.isEmpty(map1) && MapUtil.isEmpty(map2)) {
return MapUtil.newHashMap();
} else if (MapUtil.isEmpty(map1)) {
map1 = MapUtil.newHashMap();
} else if (MapUtil.isEmpty(map2)) {
map2 = MapUtil.newHashMap();
}
Set<K> key = new HashSet<>();
key.addAll(map1.keySet());
key.addAll(map2.keySet());
Map<K, V> map = new HashMap<>();
for (K t : key) {
X x = map1.get(t);
Y y = map2.get(t);
V z = merge.apply(x, y);
if (z != null) {
map.put(t, z);
}
}
return map;
}
}

View File

@ -1,32 +1,37 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import java.util.ArrayList; import cn.hutool.core.collection.CollUtil;
import java.util.Collection; import cn.hutool.core.convert.Convert;
import java.util.HashSet; import cn.hutool.core.lang.Validator;
import java.util.List; import cn.hutool.core.util.StrUtil;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.core.text.StrFormatter; import com.ruoyi.common.core.core.text.StrFormatter;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.AntPathMatcher; import org.springframework.util.AntPathMatcher;
import com.ruoyi.common.core.constant.Constants; import com.ruoyi.common.core.constant.Constants;
/** /**
* 字符串工具类 * 字符串工具类
* *
* @author ruoyi * @author ruoyi
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StringUtils extends org.apache.commons.lang3.StringUtils public class StringUtils extends org.apache.commons.lang3.StringUtils
{ {
public static final String SEPARATOR = ",";
/** 空字符串 */ /** 空字符串 */
private static final String NULLSTR = ""; private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/** /**
* 获取参数不为空值 * 获取参数不为空值
* *
* @param value defaultValue 要判断的value * @param value defaultValue 要判断的value
* @return value 返回值 * @return value 返回值
*/ */
@ -37,7 +42,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个Collection是否为空 包含ListSetQueue * * 判断一个Collection是否为空 包含ListSetQueue
* *
* @param coll 要判断的Collection * @param coll 要判断的Collection
* @return true为空 false非空 * @return true为空 false非空
*/ */
@ -48,7 +53,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个Collection是否非空包含ListSetQueue * * 判断一个Collection是否非空包含ListSetQueue
* *
* @param coll 要判断的Collection * @param coll 要判断的Collection
* @return true非空 false * @return true非空 false
*/ */
@ -59,7 +64,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个对象数组是否为空 * * 判断一个对象数组是否为空
* *
* @param objects 要判断的对象数组 * @param objects 要判断的对象数组
** @return true为空 false非空 ** @return true为空 false非空
*/ */
@ -70,7 +75,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个对象数组是否非空 * * 判断一个对象数组是否非空
* *
* @param objects 要判断的对象数组 * @param objects 要判断的对象数组
* @return true非空 false * @return true非空 false
*/ */
@ -81,7 +86,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个Map是否为空 * * 判断一个Map是否为空
* *
* @param map 要判断的Map * @param map 要判断的Map
* @return true为空 false非空 * @return true为空 false非空
*/ */
@ -92,7 +97,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个Map是否为空 * * 判断一个Map是否为空
* *
* @param map 要判断的Map * @param map 要判断的Map
* @return true非空 false * @return true非空 false
*/ */
@ -103,7 +108,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个字符串是否为空串 * * 判断一个字符串是否为空串
* *
* @param str String * @param str String
* @return true为空 false非空 * @return true为空 false非空
*/ */
@ -114,7 +119,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个字符串是否为非空串 * * 判断一个字符串是否为非空串
* *
* @param str String * @param str String
* @return true非空串 false空串 * @return true非空串 false空串
*/ */
@ -125,7 +130,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个对象是否为空 * * 判断一个对象是否为空
* *
* @param object Object * @param object Object
* @return true为空 false非空 * @return true为空 false非空
*/ */
@ -136,7 +141,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个对象是否非空 * * 判断一个对象是否非空
* *
* @param object Object * @param object Object
* @return true非空 false * @return true非空 false
*/ */
@ -147,7 +152,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* * 判断一个对象是否是数组类型Java基本型别的数组 * * 判断一个对象是否是数组类型Java基本型别的数组
* *
* @param object 对象 * @param object 对象
* @return true是数组 false不是数组 * @return true是数组 false不是数组
*/ */
@ -166,7 +171,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 截取字符串 * 截取字符串
* *
* @param str 字符串 * @param str 字符串
* @param start 开始 * @param start 开始
* @return 结果 * @return 结果
@ -197,7 +202,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 截取字符串 * 截取字符串
* *
* @param str 字符串 * @param str 字符串
* @param start 开始 * @param start 开始
* @param end 结束 * @param end 结束
@ -249,7 +254,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br> * 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br> * 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
* *
* @param template 文本模板被替换的部分用 {} 表示 * @param template 文本模板被替换的部分用 {} 表示
* @param params 参数值 * @param params 参数值
* @return 格式化后的文本 * @return 格式化后的文本
@ -265,7 +270,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 是否为http(s)://开头 * 是否为http(s)://开头
* *
* @param link 链接 * @param link 链接
* @return 结果 * @return 结果
*/ */
@ -276,7 +281,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 字符串转set * 字符串转set
* *
* @param str 字符串 * @param str 字符串
* @param sep 分隔符 * @param sep 分隔符
* @return set集合 * @return set集合
@ -288,7 +293,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 字符串转list * 字符串转list
* *
* @param str 字符串 * @param str 字符串
* @param sep 分隔符 * @param sep 分隔符
* @param filterBlank 过滤纯空白 * @param filterBlank 过滤纯空白
@ -425,7 +430,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 是否包含字符串 * 是否包含字符串
* *
* @param str 验证字符串 * @param str 验证字符串
* @param strs 字符串组 * @param strs 字符串组
* @return 包含返回true * @return 包含返回true
@ -447,81 +452,24 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 将下划线大写方式命名的字符串转换为驼峰式如果转换前的下划线大写方式命名的字符串为空则返回空字符串 例如HELLO_WORLD->HelloWorld * 将下划线大写方式命名的字符串转换为驼峰式如果转换前的下划线大写方式命名的字符串为空则返回空字符串 例如HELLO_WORLD->HelloWorld
* *
* @param name 转换前的下划线大写方式命名的字符串 * @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串 * @return 转换后的驼峰式命名的字符串
*/ */
public static String convertToCamelCase(String name) public static String convertToCamelCase(String name) {
{ return StrUtil.upperFirst(StrUtil.toCamelCase(name));
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
// 不含下划线仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty())
{
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
} }
/** /**
* 驼峰式命名法 * 驼峰式命名法 例如user_name->userName
* 例如user_name->userName
*/ */
public static String toCamelCase(String s) public static String toCamelCase(String s) {
{ return StrUtil.toCamelCase(s);
if (s == null)
{
return null;
}
if (s.indexOf(SEPARATOR) == -1)
{
return s;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
} }
/** /**
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
* *
* @param str 指定字符串 * @param str 指定字符串
* @param strs 需要检查的字符串数组 * @param strs 需要检查的字符串数组
* @return 是否匹配 * @return 是否匹配
@ -543,11 +491,11 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
} }
/** /**
* 判断url是否与规则配置: * 判断url是否与规则配置:
* ? 表示单个字符; * ? 表示单个字符;
* * 表示一层路径内的任意字符串不可跨层级; * * 表示一层路径内的任意字符串不可跨层级;
* ** 表示任意层路径; * ** 表示任意层路径;
* *
* @param pattern 匹配规则 * @param pattern 匹配规则
* @param url 需要匹配的url * @param url 需要匹配的url
* @return * @return
@ -566,7 +514,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 数字左边补齐0使之达到指定长度注意如果数字转换为字符串后长度大于size则只保留 最后size个字符 * 数字左边补齐0使之达到指定长度注意如果数字转换为字符串后长度大于size则只保留 最后size个字符
* *
* @param num 数字对象 * @param num 数字对象
* @param size 字符串指定长度 * @param size 字符串指定长度
* @return 返回数字的字符串格式该字符串为指定长度 * @return 返回数字的字符串格式该字符串为指定长度
@ -578,7 +526,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 字符串左补齐如果原始字符串s长度大于size则只保留最后size个字符 * 字符串左补齐如果原始字符串s长度大于size则只保留最后size个字符
* *
* @param s 原始字符串 * @param s 原始字符串
* @param size 字符串指定长度 * @param size 字符串指定长度
* @param c 用于补齐的字符 * @param c 用于补齐的字符
@ -612,4 +560,55 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
} }
return sb.toString(); return sb.toString();
} }
}
/**
* 切分字符串(分隔符默认逗号)
*
* @param str 被切分的字符串
* @return 分割后的数据列表
*/
public static List<String> splitList(String str) {
return splitTo(str, Convert::toStr);
}
/**
* 切分字符串
*
* @param str 被切分的字符串
* @param separator 分隔符
* @return 分割后的数据列表
*/
public static List<String> splitList(String str, String separator) {
return splitTo(str, separator, Convert::toStr);
}
/**
* 切分字符串自定义转换(分隔符默认逗号)
*
* @param str 被切分的字符串
* @param mapper 自定义转换
* @return 分割后的数据列表
*/
public static <T> List<T> splitTo(String str, Function<? super Object, T> mapper) {
return splitTo(str, SEPARATOR, mapper);
}
/**
* 切分字符串自定义转换
*
* @param str 被切分的字符串
* @param separator 分隔符
* @param mapper 自定义转换
* @return 分割后的数据列表
*/
public static <T> List<T> splitTo(String str, String separator, Function<? super Object, T> mapper) {
if (isBlank(str)) {
return new ArrayList<>(0);
}
return StrUtil.split(str, separator)
.stream()
.filter(Objects::nonNull)
.map(mapper)
.collect(Collectors.toList());
}
}

View File

@ -5,6 +5,9 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -13,10 +16,10 @@ import org.slf4j.LoggerFactory;
* *
* @author ruoyi * @author ruoyi
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Threads public class Threads
{ {
private static final Logger logger = LoggerFactory.getLogger(Threads.class); private static final Logger log = LoggerFactory.getLogger(Threads.class);
/** /**
* sleep等待,单位为毫秒 * sleep等待,单位为毫秒
*/ */
@ -51,7 +54,7 @@ public class Threads
pool.shutdownNow(); pool.shutdownNow();
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) if (!pool.awaitTermination(120, TimeUnit.SECONDS))
{ {
logger.info("Pool did not terminate"); log.info("Pool did not terminate");
} }
} }
} }
@ -93,7 +96,7 @@ public class Threads
} }
if (t != null) if (t != null)
{ {
logger.error(t.getMessage(), t); log.error(t.getMessage(), t);
} }
} }
} }

View File

@ -0,0 +1,28 @@
package com.ruoyi.common.core.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import java.util.Set;
/**
* Validator 校验框架工具
*
* @author Lion Li
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidatorUtils {
private static final Validator VALID = SpringUtils.getBean(Validator.class);
public static <T> void validate(T object, Class<?>... groups) {
Set<ConstraintViolation<T>> validate = VALID.validate(object, groups);
if (!validate.isEmpty()) {
throw new ConstraintViolationException("参数校验异常", validate);
}
}
}

View File

@ -20,12 +20,17 @@ import org.apache.commons.lang3.ArrayUtils;
import com.ruoyi.common.core.config.RuoYiConfig; import com.ruoyi.common.core.config.RuoYiConfig;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import cn.hutool.core.io.FileUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/** /**
* 文件处理工具类 * 文件处理工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileUtils @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils extends FileUtil
{ {
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
@ -74,7 +79,7 @@ public class FileUtils
*/ */
public static String writeImportBytes(byte[] data) throws IOException public static String writeImportBytes(byte[] data) throws IOException
{ {
return writeBytes(data, RuoYiConfig.getImportPath()); return writeByte(data, RuoYiConfig.getImportPath());
} }
/** /**
@ -85,7 +90,7 @@ public class FileUtils
* @return 目标文件 * @return 目标文件
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
public static String writeBytes(byte[] data, String uploadDir) throws IOException public static String writeByte(byte[] data, String uploadDir) throws IOException
{ {
FileOutputStream fos = null; FileOutputStream fos = null;
String pathName = ""; String pathName = "";

View File

@ -78,7 +78,6 @@ import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.config.RuoYiConfig; import com.ruoyi.common.core.config.RuoYiConfig;
import com.ruoyi.common.core.exception.UtilException; import com.ruoyi.common.core.exception.UtilException;
import com.ruoyi.common.core.utils.DateUtils; import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.DictUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils; import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.FileUtils; import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.core.utils.file.ImageUtils; import com.ruoyi.common.core.utils.file.ImageUtils;
@ -86,7 +85,7 @@ import com.ruoyi.common.core.utils.reflect.ReflectUtils;
/** /**
* Excel相关处理 * Excel相关处理
* *
* @author ruoyi * @author ruoyi
*/ */
public class ExcelUtil<T> public class ExcelUtil<T>
@ -283,7 +282,7 @@ public class ExcelUtil<T>
/** /**
* 对excel表单默认第一个索引名转换成list * 对excel表单默认第一个索引名转换成list
* *
* @param is 输入流 * @param is 输入流
* @return 转换后集合 * @return 转换后集合
*/ */
@ -294,7 +293,7 @@ public class ExcelUtil<T>
/** /**
* 对excel表单默认第一个索引名转换成list * 对excel表单默认第一个索引名转换成list
* *
* @param is 输入流 * @param is 输入流
* @param titleNum 标题占用行数 * @param titleNum 标题占用行数
* @return 转换后集合 * @return 转换后集合
@ -306,7 +305,7 @@ public class ExcelUtil<T>
/** /**
* 对excel表单指定表格索引名转换成list * 对excel表单指定表格索引名转换成list
* *
* @param sheetName 表格索引名 * @param sheetName 表格索引名
* @param titleNum 标题占用行数 * @param titleNum 标题占用行数
* @param is 输入流 * @param is 输入流
@ -486,7 +485,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param list 导出数据集合 * @param list 导出数据集合
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @return 结果 * @return 结果
@ -498,7 +497,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param list 导出数据集合 * @param list 导出数据集合
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @param title 标题 * @param title 标题
@ -512,7 +511,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param response 返回数据 * @param response 返回数据
* @param list 导出数据集合 * @param list 导出数据集合
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
@ -525,7 +524,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param response 返回数据 * @param response 返回数据
* @param list 导出数据集合 * @param list 导出数据集合
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
@ -542,7 +541,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @return 结果 * @return 结果
*/ */
@ -553,7 +552,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @param title 标题 * @param title 标题
* @return 结果 * @return 结果
@ -566,7 +565,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @return 结果 * @return 结果
*/ */
@ -577,7 +576,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @param title 标题 * @param title 标题
* @return 结果 * @return 结果
@ -592,7 +591,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @return 结果 * @return 结果
*/ */
public void exportExcel(HttpServletResponse response) public void exportExcel(HttpServletResponse response)
@ -614,7 +613,7 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @return 结果 * @return 结果
*/ */
public AjaxResult exportExcel() public AjaxResult exportExcel()
@ -682,7 +681,7 @@ public class ExcelUtil<T>
/** /**
* 填充excel数据 * 填充excel数据
* *
* @param index 序号 * @param index 序号
* @param row 单元格行 * @param row 单元格行
*/ */
@ -753,7 +752,7 @@ public class ExcelUtil<T>
/** /**
* 创建表格样式 * 创建表格样式
* *
* @param wb 工作薄对象 * @param wb 工作薄对象
* @return 样式列表 * @return 样式列表
*/ */
@ -806,7 +805,7 @@ public class ExcelUtil<T>
/** /**
* 根据Excel注解创建表格头样式 * 根据Excel注解创建表格头样式
* *
* @param wb 工作薄对象 * @param wb 工作薄对象
* @return 自定义样式列表 * @return 自定义样式列表
*/ */
@ -839,7 +838,7 @@ public class ExcelUtil<T>
/** /**
* 根据Excel注解创建表格列样式 * 根据Excel注解创建表格列样式
* *
* @param wb 工作薄对象 * @param wb 工作薄对象
* @return 自定义样式列表 * @return 自定义样式列表
*/ */
@ -901,7 +900,7 @@ public class ExcelUtil<T>
/** /**
* 设置单元格信息 * 设置单元格信息
* *
* @param value 单元格值 * @param value 单元格值
* @param attr 注解相关 * @param attr 注解相关
* @param cell 单元格信息 * @param cell 单元格信息
@ -1070,7 +1069,7 @@ public class ExcelUtil<T>
/** /**
* 设置 POI XSSFSheet 单元格提示或选择框 * 设置 POI XSSFSheet 单元格提示或选择框
* *
* @param sheet 表单 * @param sheet 表单
* @param textlist 下拉框显示的内容 * @param textlist 下拉框显示的内容
* @param promptContent 提示内容 * @param promptContent 提示内容
@ -1107,7 +1106,7 @@ public class ExcelUtil<T>
/** /**
* 设置某些列的值只能输入预制的数据,显示下拉框兼容超出一定数量的下拉框. * 设置某些列的值只能输入预制的数据,显示下拉框兼容超出一定数量的下拉框.
* *
* @param sheet 要设置的sheet. * @param sheet 要设置的sheet.
* @param textlist 下拉框显示的内容 * @param textlist 下拉框显示的内容
* @param promptContent 提示内容 * @param promptContent 提示内容
@ -1159,7 +1158,7 @@ public class ExcelUtil<T>
/** /**
* 解析导出值 0=,1=,2=未知 * 解析导出值 0=,1=,2=未知
* *
* @param propertyValue 参数值 * @param propertyValue 参数值
* @param converterExp 翻译注解 * @param converterExp 翻译注解
* @param separator 分隔符 * @param separator 分隔符
@ -1196,7 +1195,7 @@ public class ExcelUtil<T>
/** /**
* 反向解析值 =0,=1,未知=2 * 反向解析值 =0,=1,未知=2
* *
* @param propertyValue 参数值 * @param propertyValue 参数值
* @param converterExp 翻译注解 * @param converterExp 翻译注解
* @param separator 分隔符 * @param separator 分隔符
@ -1233,7 +1232,7 @@ public class ExcelUtil<T>
/** /**
* 解析字典值 * 解析字典值
* *
* @param dictValue 字典值 * @param dictValue 字典值
* @param dictType 字典类型 * @param dictType 字典类型
* @param separator 分隔符 * @param separator 分隔符
@ -1241,12 +1240,13 @@ public class ExcelUtil<T>
*/ */
public static String convertDictByExp(String dictValue, String dictType, String separator) public static String convertDictByExp(String dictValue, String dictType, String separator)
{ {
return DictUtils.getDictLabel(dictType, dictValue, separator); //return DictUtils.getDictLabel(dictType, dictValue, separator);
return "";
} }
/** /**
* 反向解析值字典值 * 反向解析值字典值
* *
* @param dictLabel 字典标签 * @param dictLabel 字典标签
* @param dictType 字典类型 * @param dictType 字典类型
* @param separator 分隔符 * @param separator 分隔符
@ -1254,12 +1254,13 @@ public class ExcelUtil<T>
*/ */
public static String reverseDictByExp(String dictLabel, String dictType, String separator) public static String reverseDictByExp(String dictLabel, String dictType, String separator)
{ {
return DictUtils.getDictValue(dictType, dictLabel, separator); //return DictUtils.getDictValue(dictType, dictLabel, separator);
return "";
} }
/** /**
* 数据处理器 * 数据处理器
* *
* @param value 数据值 * @param value 数据值
* @param excel 数据注解 * @param excel 数据注解
* @return * @return
@ -1336,7 +1337,7 @@ public class ExcelUtil<T>
/** /**
* 获取下载路径 * 获取下载路径
* *
* @param filename 文件名称 * @param filename 文件名称
*/ */
public String getAbsoluteFile(String filename) public String getAbsoluteFile(String filename)
@ -1352,7 +1353,7 @@ public class ExcelUtil<T>
/** /**
* 获取bean中的属性值 * 获取bean中的属性值
* *
* @param vo 实体对象 * @param vo 实体对象
* @param field 字段 * @param field 字段
* @param excel 注解 * @param excel 注解
@ -1383,7 +1384,7 @@ public class ExcelUtil<T>
/** /**
* 以类的属性的get方法方法形式获取值 * 以类的属性的get方法方法形式获取值
* *
* @param o * @param o
* @param name * @param name
* @return value * @return value
@ -1489,7 +1490,7 @@ public class ExcelUtil<T>
/** /**
* 创建工作表 * 创建工作表
* *
* @param sheetNo sheet数量 * @param sheetNo sheet数量
* @param index 序号 * @param index 序号
*/ */
@ -1506,7 +1507,7 @@ public class ExcelUtil<T>
/** /**
* 获取单元格值 * 获取单元格值
* *
* @param row 获取的行 * @param row 获取的行
* @param column 获取单元格列号 * @param column 获取单元格列号
* @return 单元格值 * @return 单元格值
@ -1566,7 +1567,7 @@ public class ExcelUtil<T>
/** /**
* 判断是否是空行 * 判断是否是空行
* *
* @param row 判断的行 * @param row 判断的行
* @return * @return
*/ */
@ -1654,7 +1655,7 @@ public class ExcelUtil<T>
/** /**
* 格式化不同类型的日期对象 * 格式化不同类型的日期对象
* *
* @param dateFormat 日期格式 * @param dateFormat 日期格式
* @param val 被格式化的日期对象 * @param val 被格式化的日期对象
* @return 格式化后的日期字符 * @return 格式化后的日期字符
@ -1720,7 +1721,7 @@ public class ExcelUtil<T>
/** /**
* 获取对象的子列表方法 * 获取对象的子列表方法
* *
* @param name 名称 * @param name 名称
* @param pojoClass 类对象 * @param pojoClass 类对象
* @return 子列表方法 * @return 子列表方法

View File

@ -1,5 +1,6 @@
package com.ruoyi.common.core.utils.reflect; package com.ruoyi.common.core.utils.reflect;
import cn.hutool.core.util.ReflectUtil;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -18,11 +19,11 @@ import org.slf4j.LoggerFactory;
/** /**
* 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
* *
* @author ruoyi * @author ruoyi
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ReflectUtils public class ReflectUtils extends ReflectUtil
{ {
private static final String SETTER_PREFIX = "set"; private static final String SETTER_PREFIX = "set";
@ -71,51 +72,51 @@ public class ReflectUtils
} }
} }
/** // /**
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. // * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
*/ // */
@SuppressWarnings("unchecked") // @SuppressWarnings("unchecked")
public static <E> E getFieldValue(final Object obj, final String fieldName) // public static <E> E getFieldValue(final Object obj, final String fieldName)
{ // {
Field field = getAccessibleField(obj, fieldName); // Field field = getAccessibleField(obj, fieldName);
if (field == null) // if (field == null)
{ // {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); // logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return null; // return null;
} // }
E result = null; // E result = null;
try // try
{ // {
result = (E) field.get(obj); // result = (E) field.get(obj);
} // }
catch (IllegalAccessException e) // catch (IllegalAccessException e)
{ // {
logger.error("不可能抛出的异常{}", e.getMessage()); // logger.error("不可能抛出的异常{}", e.getMessage());
} // }
return result; // return result;
} // }
//
/** // /**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. // * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*/ // */
public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) // public static <E> void setFieldValue(final Object obj, final String fieldName, final E value)
{ // {
Field field = getAccessibleField(obj, fieldName); // Field field = getAccessibleField(obj, fieldName);
if (field == null) // if (field == null)
{ // {
// throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); // // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); // logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return; // return;
} // }
try // try
{ // {
field.set(obj, value); // field.set(obj, value);
} // }
catch (IllegalAccessException e) // catch (IllegalAccessException e)
{ // {
logger.error("不可能抛出的异常: {}", e.getMessage()); // logger.error("不可能抛出的异常: {}", e.getMessage());
} // }
} // }
/** /**
* 直接调用对象方法, 无视private/protected修饰符. * 直接调用对象方法, 无视private/protected修饰符.

Some files were not shown because too many files have changed in this diff Show More