升级到JDK21,SpringBoot3.1.8,SpringCloud2022.0.5
parent
c3de97c825
commit
4039d79e5a
50
pom.xml
50
pom.xml
|
|
@ -14,23 +14,25 @@
|
|||
<ruoyi.version>3.6.3</ruoyi.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<java.version>21</java.version>
|
||||
|
||||
<spring-boot.version>2.7.18</spring-boot.version>
|
||||
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
|
||||
<spring-boot-admin.version>2.7.11</spring-boot-admin.version>
|
||||
<spring-boot.version>3.1.8</spring-boot.version>
|
||||
<spring-cloud.version>2022.0.5</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
|
||||
<spring-boot-admin.version>3.1.8</spring-boot-admin.version>
|
||||
<nacos-client.version>2.3.0</nacos-client.version>
|
||||
<swagger.fox.version>3.0.0</swagger.fox.version>
|
||||
<swagger.core.version>1.6.2</swagger.core.version>
|
||||
<swagger.springdoc.version>2.3.0</swagger.springdoc.version>
|
||||
<swagger.core.version>2.2.20</swagger.core.version>
|
||||
<tobato.version>1.27.2</tobato.version>
|
||||
<kaptcha.version>2.3.3</kaptcha.version>
|
||||
<pagehelper.boot.version>2.0.0</pagehelper.boot.version>
|
||||
<druid.version>1.2.20</druid.version>
|
||||
<dynamic-ds.version>4.2.0</dynamic-ds.version>
|
||||
<commons.io.version>2.13.0</commons.io.version>
|
||||
<pagehelper.boot.version>2.1.0</pagehelper.boot.version>
|
||||
<druid.version>1.2.21</druid.version>
|
||||
<dynamic-ds.version>4.3.0</dynamic-ds.version>
|
||||
<commons.io.version>2.15.1</commons.io.version>
|
||||
<velocity.version>2.3</velocity.version>
|
||||
<fastjson.version>2.0.43</fastjson.version>
|
||||
<jjwt.version>0.9.1</jjwt.version>
|
||||
<fastjson.version>2.0.45</fastjson.version>
|
||||
<jjwt.version>0.12.4</jjwt.version>
|
||||
<minio.version>8.2.2</minio.version>
|
||||
<poi.version>4.1.2</poi.version>
|
||||
<transmittable-thread-local.version>2.14.4</transmittable-thread-local.version>
|
||||
|
|
@ -76,14 +78,14 @@
|
|||
|
||||
<!-- Swagger 依赖配置 -->
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-models</artifactId>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger.core.version}</version>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${swagger.springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 验证码 -->
|
||||
|
|
@ -131,7 +133,12 @@
|
|||
<!-- JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
|
@ -142,6 +149,13 @@
|
|||
<version>${transmittable-thread-local.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- druid强制覆盖 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 核心模块 -->
|
||||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
|
|
|
|||
|
|
@ -15,29 +15,28 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
|
||||
/**
|
||||
* 用户服务
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
|
||||
public interface RemoteUserService
|
||||
{
|
||||
public interface RemoteUserService {
|
||||
/**
|
||||
* 通过用户名查询用户信息
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param source 请求来源
|
||||
* @param source 请求来源
|
||||
* @return 结果
|
||||
*/
|
||||
@GetMapping("/user/info/{username}")
|
||||
public R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
|
||||
R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
|
||||
|
||||
/**
|
||||
* 注册用户信息
|
||||
*
|
||||
* @param sysUser 用户信息
|
||||
* @param source 请求来源
|
||||
* @param source 请求来源
|
||||
* @return 结果
|
||||
*/
|
||||
@PostMapping("/user/register")
|
||||
public R<Boolean> registerUserInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
|
||||
R<Boolean> registerUserInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
package com.ruoyi.system.api.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
|
@ -17,6 +18,7 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
|
|||
*/
|
||||
public class SysDept extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 部门ID */
|
||||
|
|
@ -53,7 +55,7 @@ public class SysDept extends BaseEntity
|
|||
private String parentName;
|
||||
|
||||
/** 子部门 */
|
||||
private List<SysDept> children = new ArrayList<SysDept>();
|
||||
private List<SysDept> children = new ArrayList<>();
|
||||
|
||||
public Long getDeptId()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package com.ruoyi.system.api.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
|
|
@ -9,6 +9,8 @@ import com.ruoyi.common.core.annotation.Excel.ColumnType;
|
|||
import com.ruoyi.common.core.constant.UserConstants;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 字典数据表 sys_dict_data
|
||||
*
|
||||
|
|
@ -16,6 +18,7 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
|
|||
*/
|
||||
public class SysDictData extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 字典编码 */
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
package com.ruoyi.system.api.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
import com.ruoyi.common.core.annotation.Excel.ColumnType;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 字典类型表 sys_dict_type
|
||||
*
|
||||
|
|
@ -16,6 +18,7 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
|
|||
*/
|
||||
public class SysDictType extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 字典主键 */
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
package com.ruoyi.system.api.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.Set;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
|
|
@ -17,6 +18,7 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
|
|||
*/
|
||||
public class SysRole extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 角色ID */
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
package com.ruoyi.system.api.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.*;
|
||||
import jakarta.validation.constraints.*;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
|
|
@ -19,6 +20,7 @@ import com.ruoyi.common.core.xss.Xss;
|
|||
*/
|
||||
public class SysUser extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 用户ID */
|
||||
|
|
|
|||
|
|
@ -21,19 +21,25 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- SpringCloud Alibaba Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- SpringBoot Web -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
|
@ -45,7 +51,7 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- RuoYi Common Security-->
|
||||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
|
|
@ -53,7 +59,7 @@
|
|||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
|
|
|
|||
|
|
@ -17,15 +17,6 @@ public class RuoYiAuthApplication
|
|||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(RuoYiAuthApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package com.ruoyi.auth.controller;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
|
@ -19,12 +19,11 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
|
||||
/**
|
||||
* token 控制
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
public class TokenController
|
||||
{
|
||||
public class TokenController {
|
||||
@Autowired
|
||||
private TokenService tokenService;
|
||||
|
||||
|
|
@ -32,8 +31,7 @@ public class TokenController
|
|||
private SysLoginService sysLoginService;
|
||||
|
||||
@PostMapping("login")
|
||||
public R<?> login(@RequestBody LoginBody form)
|
||||
{
|
||||
public R<?> login(@RequestBody LoginBody form) {
|
||||
// 用户登录
|
||||
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
|
||||
// 获取登录token
|
||||
|
|
@ -41,11 +39,9 @@ public class TokenController
|
|||
}
|
||||
|
||||
@DeleteMapping("logout")
|
||||
public R<?> logout(HttpServletRequest request)
|
||||
{
|
||||
public R<?> logout(HttpServletRequest request) {
|
||||
String token = SecurityUtils.getToken(request);
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token)) {
|
||||
String username = JwtUtils.getUserName(token);
|
||||
// 删除用户缓存记录
|
||||
AuthUtil.logoutByToken(token);
|
||||
|
|
@ -56,11 +52,9 @@ public class TokenController
|
|||
}
|
||||
|
||||
@PostMapping("refresh")
|
||||
public R<?> refresh(HttpServletRequest request)
|
||||
{
|
||||
public R<?> refresh(HttpServletRequest request) {
|
||||
LoginUser loginUser = tokenService.getLoginUser(request);
|
||||
if (StringUtils.isNotNull(loginUser))
|
||||
{
|
||||
if (StringUtils.isNotNull(loginUser)) {
|
||||
// 刷新令牌有效期
|
||||
tokenService.refreshToken(loginUser);
|
||||
return R.ok();
|
||||
|
|
@ -69,8 +63,7 @@ public class TokenController
|
|||
}
|
||||
|
||||
@PostMapping("register")
|
||||
public R<?> register(@RequestBody RegisterBody registerBody)
|
||||
{
|
||||
public R<?> register(@RequestBody RegisterBody registerBody) {
|
||||
// 用户注册
|
||||
sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
|
||||
return R.ok();
|
||||
|
|
|
|||
|
|
@ -1,31 +1,31 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="logs/ruoyi-auth" />
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
|
||||
<property name="log.path" value="logs/ruoyi-auth"/>
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n"/>
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${log.pattern}</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${log.pattern}</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 系统日志输出 -->
|
||||
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/info.log</file>
|
||||
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/info.log</file>
|
||||
<!-- 循环政策:基于时间创建日志文件 -->
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<!-- 日志文件名格式 -->
|
||||
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<!-- 日志最大的历史 60天 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>${log.pattern}</pattern>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<!-- 日志最大的历史 60天 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>${log.pattern}</pattern>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<!-- 过滤的级别 -->
|
||||
<level>INFO</level>
|
||||
<!-- 匹配时的操作:接收(记录) -->
|
||||
|
|
@ -33,16 +33,16 @@
|
|||
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||
<onMismatch>DENY</onMismatch>
|
||||
</filter>
|
||||
</appender>
|
||||
</appender>
|
||||
|
||||
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/error.log</file>
|
||||
<file>${log.path}/error.log</file>
|
||||
<!-- 循环政策:基于时间创建日志文件 -->
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<!-- 日志文件名格式 -->
|
||||
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<!-- 日志最大的历史 60天 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
<!-- 日志最大的历史 60天 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>${log.pattern}</pattern>
|
||||
|
|
@ -50,25 +50,25 @@
|
|||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<!-- 过滤的级别 -->
|
||||
<level>ERROR</level>
|
||||
<!-- 匹配时的操作:接收(记录) -->
|
||||
<!-- 匹配时的操作:接收(记录) -->
|
||||
<onMatch>ACCEPT</onMatch>
|
||||
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||
<onMismatch>DENY</onMismatch>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<!-- 系统模块日志级别控制 -->
|
||||
<logger name="com.ruoyi" level="info" />
|
||||
<!-- Spring日志级别控制 -->
|
||||
<logger name="org.springframework" level="warn" />
|
||||
<logger name="com.ruoyi" level="info"/>
|
||||
<!-- Spring日志级别控制 -->
|
||||
<logger name="org.springframework" level="warn"/>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="console" />
|
||||
</root>
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="file_info" />
|
||||
<appender-ref ref="file_error" />
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="file_info"/>
|
||||
<appender-ref ref="file_error"/>
|
||||
</root>
|
||||
</configuration>
|
||||
|
|
@ -47,7 +47,7 @@
|
|||
<artifactId>transmittable-thread-local</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Pagehelper -->
|
||||
<!-- PageHelper -->
|
||||
<dependency>
|
||||
<groupId>com.github.pagehelper</groupId>
|
||||
<artifactId>pagehelper-spring-boot-starter</artifactId>
|
||||
|
|
@ -74,15 +74,20 @@
|
|||
<!-- Jwt -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Jaxb -->
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<groupId>jakarta.xml.bind</groupId>
|
||||
<artifactId>jakarta.xml.bind-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Apache Lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
|
@ -103,13 +108,13 @@
|
|||
|
||||
<!-- Java Servlet -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Swagger -->
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
|
|
|||
|
|
@ -4,178 +4,172 @@ import java.lang.annotation.ElementType;
|
|||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
|
||||
|
||||
/**
|
||||
* 自定义导出Excel数据注解
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface Excel
|
||||
{
|
||||
public @interface Excel {
|
||||
/**
|
||||
* 导出时在excel中排序
|
||||
*/
|
||||
public int sort() default Integer.MAX_VALUE;
|
||||
int sort() default Integer.MAX_VALUE;
|
||||
|
||||
/**
|
||||
* 导出到Excel中的名字.
|
||||
*/
|
||||
public String name() default "";
|
||||
String name() default "";
|
||||
|
||||
/**
|
||||
* 日期格式, 如: yyyy-MM-dd
|
||||
*/
|
||||
public String dateFormat() default "";
|
||||
String dateFormat() default "";
|
||||
|
||||
/**
|
||||
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
|
||||
*/
|
||||
public String readConverterExp() default "";
|
||||
String readConverterExp() default "";
|
||||
|
||||
/**
|
||||
* 分隔符,读取字符串组内容
|
||||
*/
|
||||
public String separator() default ",";
|
||||
String separator() default ",";
|
||||
|
||||
/**
|
||||
* BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
|
||||
*/
|
||||
public int scale() default -1;
|
||||
int scale() default -1;
|
||||
|
||||
/**
|
||||
* BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
|
||||
*/
|
||||
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
|
||||
RoundingMode roundingMode() default RoundingMode.HALF_EVEN;
|
||||
|
||||
/**
|
||||
* 导出时在excel中每个列的高度
|
||||
*/
|
||||
public double height() default 14;
|
||||
double height() default 14;
|
||||
|
||||
/**
|
||||
* 导出时在excel中每个列的宽度
|
||||
*/
|
||||
public double width() default 16;
|
||||
double width() default 16;
|
||||
|
||||
/**
|
||||
* 文字后缀,如% 90 变成90%
|
||||
*/
|
||||
public String suffix() default "";
|
||||
String suffix() default "";
|
||||
|
||||
/**
|
||||
* 当值为空时,字段的默认值
|
||||
*/
|
||||
public String defaultValue() default "";
|
||||
String defaultValue() default "";
|
||||
|
||||
/**
|
||||
* 提示信息
|
||||
*/
|
||||
public String prompt() default "";
|
||||
String prompt() default "";
|
||||
|
||||
/**
|
||||
* 设置只能选择不能输入的列内容.
|
||||
*/
|
||||
public String[] combo() default {};
|
||||
String[] combo() default {};
|
||||
|
||||
/**
|
||||
* 是否需要纵向合并单元格,应对需求:含有list集合单元格)
|
||||
*/
|
||||
public boolean needMerge() default false;
|
||||
boolean needMerge() default false;
|
||||
|
||||
/**
|
||||
* 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
|
||||
*/
|
||||
public boolean isExport() default true;
|
||||
boolean isExport() default true;
|
||||
|
||||
/**
|
||||
* 另一个类中的属性名称,支持多级获取,以小数点隔开
|
||||
*/
|
||||
public String targetAttr() default "";
|
||||
String targetAttr() default "";
|
||||
|
||||
/**
|
||||
* 是否自动统计数据,在最后追加一行统计数据总和
|
||||
*/
|
||||
public boolean isStatistics() default false;
|
||||
boolean isStatistics() default false;
|
||||
|
||||
/**
|
||||
* 导出类型(0数字 1字符串)
|
||||
*/
|
||||
public ColumnType cellType() default ColumnType.STRING;
|
||||
ColumnType cellType() default ColumnType.STRING;
|
||||
|
||||
/**
|
||||
* 导出列头背景颜色
|
||||
*/
|
||||
public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
|
||||
IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
|
||||
|
||||
/**
|
||||
* 导出列头字体颜色
|
||||
*/
|
||||
public IndexedColors headerColor() default IndexedColors.WHITE;
|
||||
IndexedColors headerColor() default IndexedColors.WHITE;
|
||||
|
||||
/**
|
||||
* 导出单元格背景颜色
|
||||
*/
|
||||
public IndexedColors backgroundColor() default IndexedColors.WHITE;
|
||||
IndexedColors backgroundColor() default IndexedColors.WHITE;
|
||||
|
||||
/**
|
||||
* 导出单元格字体颜色
|
||||
*/
|
||||
public IndexedColors color() default IndexedColors.BLACK;
|
||||
IndexedColors color() default IndexedColors.BLACK;
|
||||
|
||||
/**
|
||||
* 导出字段对齐方式
|
||||
*/
|
||||
public HorizontalAlignment align() default HorizontalAlignment.CENTER;
|
||||
HorizontalAlignment align() default HorizontalAlignment.CENTER;
|
||||
|
||||
/**
|
||||
* 自定义数据处理器
|
||||
*/
|
||||
public Class<?> handler() default ExcelHandlerAdapter.class;
|
||||
Class<?> handler() default ExcelHandlerAdapter.class;
|
||||
|
||||
/**
|
||||
* 自定义数据处理器参数
|
||||
*/
|
||||
public String[] args() default {};
|
||||
String[] args() default {};
|
||||
|
||||
/**
|
||||
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
|
||||
*/
|
||||
Type type() default Type.ALL;
|
||||
|
||||
public enum Type
|
||||
{
|
||||
enum Type {
|
||||
ALL(0), EXPORT(1), IMPORT(2);
|
||||
private final int value;
|
||||
|
||||
Type(int value)
|
||||
{
|
||||
Type(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int value()
|
||||
{
|
||||
int value() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
|
||||
public enum ColumnType
|
||||
{
|
||||
enum ColumnType {
|
||||
NUMERIC(0), STRING(1), IMAGE(2);
|
||||
private final int value;
|
||||
|
||||
ColumnType(int value)
|
||||
{
|
||||
ColumnType(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int value()
|
||||
{
|
||||
int value() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,6 @@ public class TokenConstants
|
|||
/**
|
||||
* 令牌秘钥
|
||||
*/
|
||||
public final static String SECRET = "abcdefghijklmnopqrstuvwxyz";
|
||||
public final static String SECRET = "NpdMXhdDbQM6YzdbLs8NsQqUjGtKBuGIbRWr8js6GLcdjr2GR0WbWS3guDlymBAN";
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,23 @@
|
|||
package com.ruoyi.common.core.utils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.constant.TokenConstants;
|
||||
import com.ruoyi.common.core.text.Convert;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
/**
|
||||
* Jwt工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class JwtUtils
|
||||
{
|
||||
public class JwtUtils {
|
||||
public static String secret = TokenConstants.SECRET;
|
||||
|
||||
/**
|
||||
|
|
@ -23,9 +26,11 @@ public class JwtUtils
|
|||
* @param claims 数据声明
|
||||
* @return 令牌
|
||||
*/
|
||||
public static String createToken(Map<String, Object> claims)
|
||||
{
|
||||
String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
|
||||
public static String createToken(Map<String, Object> claims) {
|
||||
String token = Jwts.builder()
|
||||
.claims(claims)
|
||||
.signWith(getSigningKey(secret), Jwts.SIG.HS512)
|
||||
.compact();
|
||||
return token;
|
||||
}
|
||||
|
||||
|
|
@ -35,89 +40,90 @@ public class JwtUtils
|
|||
* @param token 令牌
|
||||
* @return 数据声明
|
||||
*/
|
||||
public static Claims parseToken(String token)
|
||||
{
|
||||
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
|
||||
public static Claims parseToken(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey(secret))
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据令牌获取用户标识
|
||||
*
|
||||
*
|
||||
* @param token 令牌
|
||||
* @return 用户ID
|
||||
*/
|
||||
public static String getUserKey(String token)
|
||||
{
|
||||
public static String getUserKey(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return getValue(claims, SecurityConstants.USER_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据令牌获取用户标识
|
||||
*
|
||||
*
|
||||
* @param claims 身份信息
|
||||
* @return 用户ID
|
||||
*/
|
||||
public static String getUserKey(Claims claims)
|
||||
{
|
||||
public static String getUserKey(Claims claims) {
|
||||
return getValue(claims, SecurityConstants.USER_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据令牌获取用户ID
|
||||
*
|
||||
*
|
||||
* @param token 令牌
|
||||
* @return 用户ID
|
||||
*/
|
||||
public static String getUserId(String token)
|
||||
{
|
||||
public static String getUserId(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return getValue(claims, SecurityConstants.DETAILS_USER_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据身份信息获取用户ID
|
||||
*
|
||||
*
|
||||
* @param claims 身份信息
|
||||
* @return 用户ID
|
||||
*/
|
||||
public static String getUserId(Claims claims)
|
||||
{
|
||||
public static String getUserId(Claims claims) {
|
||||
return getValue(claims, SecurityConstants.DETAILS_USER_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据令牌获取用户名
|
||||
*
|
||||
*
|
||||
* @param token 令牌
|
||||
* @return 用户名
|
||||
*/
|
||||
public static String getUserName(String token)
|
||||
{
|
||||
public static String getUserName(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return getValue(claims, SecurityConstants.DETAILS_USERNAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据身份信息获取用户名
|
||||
*
|
||||
*
|
||||
* @param claims 身份信息
|
||||
* @return 用户名
|
||||
*/
|
||||
public static String getUserName(Claims claims)
|
||||
{
|
||||
public static String getUserName(Claims claims) {
|
||||
return getValue(claims, SecurityConstants.DETAILS_USERNAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据身份信息获取键值
|
||||
*
|
||||
*
|
||||
* @param claims 身份信息
|
||||
* @param key 键
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public static String getValue(Claims claims, String key)
|
||||
{
|
||||
public static String getValue(Claims claims, String key) {
|
||||
return Convert.toStr(claims.get(key), "");
|
||||
}
|
||||
|
||||
private static SecretKey getSigningKey(String secret) {
|
||||
byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ import java.util.Collections;
|
|||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import jakarta.servlet.ServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
package com.ruoyi.common.core.utils.bean;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import jakarta.validation.Validator;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import javax.validation.Validator;
|
||||
|
||||
/**
|
||||
* bean对象属性验证
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import java.io.OutputStream;
|
|||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
|
||||
|
|
|
|||
|
|
@ -2,9 +2,11 @@ package com.ruoyi.common.core.utils.file;
|
|||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
|
@ -14,70 +16,53 @@ import org.slf4j.LoggerFactory;
|
|||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class ImageUtils
|
||||
{
|
||||
public class ImageUtils {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
|
||||
|
||||
public static byte[] getImage(String imagePath)
|
||||
{
|
||||
public static byte[] getImage(String imagePath) {
|
||||
InputStream is = getFile(imagePath);
|
||||
try
|
||||
{
|
||||
try {
|
||||
return IOUtils.toByteArray(is);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("图片加载异常 {}", e);
|
||||
} catch (Exception e) {
|
||||
log.error("图片加载异常", e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
} finally {
|
||||
IOUtils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream getFile(String imagePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
public static InputStream getFile(String imagePath) {
|
||||
try {
|
||||
byte[] result = readFile(imagePath);
|
||||
result = Arrays.copyOf(result, result.length);
|
||||
return new ByteArrayInputStream(result);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("获取图片异常 {}", e);
|
||||
} catch (Exception e) {
|
||||
log.error("获取图片异常", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件为字节数据
|
||||
*
|
||||
*
|
||||
* @param url 地址
|
||||
* @return 字节数据
|
||||
*/
|
||||
public static byte[] readFile(String url)
|
||||
{
|
||||
public static byte[] readFile(String url) {
|
||||
InputStream in = null;
|
||||
try
|
||||
{
|
||||
try {
|
||||
// 网络地址
|
||||
URL urlObj = new URL(url);
|
||||
URL urlObj = URI.create(url).toURL();
|
||||
URLConnection urlConnection = urlObj.openConnection();
|
||||
urlConnection.setConnectTimeout(30 * 1000);
|
||||
urlConnection.setReadTimeout(60 * 1000);
|
||||
urlConnection.setDoInput(true);
|
||||
in = urlConnection.getInputStream();
|
||||
return IOUtils.toByteArray(in);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("访问文件异常 {}", e);
|
||||
} catch (Exception e) {
|
||||
log.error("访问文件异常", e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
} finally {
|
||||
IOUtils.closeQuietly(in);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package com.ruoyi.common.core.utils.ip;
|
|||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -6,7 +6,9 @@ import java.lang.reflect.Method;
|
|||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
|
|
@ -17,32 +19,29 @@ import com.ruoyi.common.core.utils.DateUtils;
|
|||
|
||||
/**
|
||||
* 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class ReflectUtils
|
||||
{
|
||||
public class ReflectUtils {
|
||||
private static final String SETTER_PREFIX = "set";
|
||||
|
||||
private static final String GETTER_PREFIX = "get";
|
||||
|
||||
private static final String CGLIB_CLASS_SEPARATOR = "$$";
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
|
||||
private final static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
|
||||
|
||||
/**
|
||||
* 调用Getter方法.
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E invokeGetter(Object obj, String propertyName)
|
||||
{
|
||||
public static <E> E invokeGetter(Object obj, String propertyName) {
|
||||
Object object = obj;
|
||||
for (String name : StringUtils.split(propertyName, "."))
|
||||
{
|
||||
for (String name : StringUtils.split(propertyName, ".")) {
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
|
||||
}
|
||||
return (E) object;
|
||||
}
|
||||
|
|
@ -51,21 +50,16 @@ public class ReflectUtils
|
|||
* 调用Setter方法, 仅匹配方法名。
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static <E> void invokeSetter(Object obj, String propertyName, E value)
|
||||
{
|
||||
public static <E> void invokeSetter(Object obj, String propertyName, E value) {
|
||||
Object object = obj;
|
||||
String[] names = StringUtils.split(propertyName, ".");
|
||||
for (int i = 0; i < names.length; i++)
|
||||
{
|
||||
if (i < names.length - 1)
|
||||
{
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
if (i < names.length - 1) {
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
}
|
||||
else
|
||||
{
|
||||
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
|
||||
} else {
|
||||
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
invokeMethodByName(object, setterMethodName, new Object[] { value });
|
||||
invokeMethodByName(object, setterMethodName, new Object[]{value});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -74,21 +68,16 @@ public class ReflectUtils
|
|||
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
|
||||
*/
|
||||
@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);
|
||||
if (field == null)
|
||||
{
|
||||
if (field == null) {
|
||||
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
|
||||
return null;
|
||||
}
|
||||
E result = null;
|
||||
try
|
||||
{
|
||||
try {
|
||||
result = (E) field.get(obj);
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常{}", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
|
|
@ -97,21 +86,16 @@ public class ReflectUtils
|
|||
/**
|
||||
* 直接设置对象属性值, 无视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);
|
||||
if (field == null)
|
||||
{
|
||||
if (field == null) {
|
||||
// throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
|
||||
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
try {
|
||||
field.set(obj, value);
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
|
@ -123,25 +107,19 @@ public class ReflectUtils
|
|||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
|
||||
final Object[] args)
|
||||
{
|
||||
if (obj == null || methodName == null)
|
||||
{
|
||||
final Object[] args) {
|
||||
if (obj == null || methodName == null) {
|
||||
return null;
|
||||
}
|
||||
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
|
||||
if (method == null)
|
||||
{
|
||||
if (method == null) {
|
||||
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
try {
|
||||
return (E) method.invoke(obj, args);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
|
||||
} catch (Exception e) {
|
||||
String msg = "method: " + method + ", obj: " + obj + ", args: " + Arrays.toString(args);
|
||||
throw convertReflectionExceptionToUnchecked(msg, e);
|
||||
}
|
||||
}
|
||||
|
|
@ -152,69 +130,45 @@ public class ReflectUtils
|
|||
* 只匹配函数名,如果有多个同名函数调用第一个。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
|
||||
{
|
||||
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
|
||||
Method method = getAccessibleMethodByName(obj, methodName, args.length);
|
||||
if (method == null)
|
||||
{
|
||||
if (method == null) {
|
||||
// 如果为空不报错,直接返回空。
|
||||
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
try {
|
||||
// 类型转换(将参数数据类型转换为目标方法参数类型)
|
||||
Class<?>[] cs = method.getParameterTypes();
|
||||
for (int i = 0; i < cs.length; i++)
|
||||
{
|
||||
if (args[i] != null && !args[i].getClass().equals(cs[i]))
|
||||
{
|
||||
if (cs[i] == String.class)
|
||||
{
|
||||
for (int i = 0; i < cs.length; i++) {
|
||||
if (args[i] != null && !args[i].getClass().equals(cs[i])) {
|
||||
if (cs[i] == String.class) {
|
||||
args[i] = Convert.toStr(args[i]);
|
||||
if (StringUtils.endsWith((String) args[i], ".0"))
|
||||
{
|
||||
if (StringUtils.endsWith((String) args[i], ".0")) {
|
||||
args[i] = StringUtils.substringBefore((String) args[i], ".0");
|
||||
}
|
||||
}
|
||||
else if (cs[i] == Integer.class)
|
||||
{
|
||||
} else if (cs[i] == Integer.class) {
|
||||
args[i] = Convert.toInt(args[i]);
|
||||
}
|
||||
else if (cs[i] == Long.class)
|
||||
{
|
||||
} else if (cs[i] == Long.class) {
|
||||
args[i] = Convert.toLong(args[i]);
|
||||
}
|
||||
else if (cs[i] == Double.class)
|
||||
{
|
||||
} else if (cs[i] == Double.class) {
|
||||
args[i] = Convert.toDouble(args[i]);
|
||||
}
|
||||
else if (cs[i] == Float.class)
|
||||
{
|
||||
} else if (cs[i] == Float.class) {
|
||||
args[i] = Convert.toFloat(args[i]);
|
||||
}
|
||||
else if (cs[i] == Date.class)
|
||||
{
|
||||
if (args[i] instanceof String)
|
||||
{
|
||||
} else if (cs[i] == Date.class) {
|
||||
if (args[i] instanceof String) {
|
||||
args[i] = DateUtils.parseDate(args[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
args[i] = DateUtil.getJavaDate((Double) args[i]);
|
||||
}
|
||||
}
|
||||
else if (cs[i] == boolean.class || cs[i] == Boolean.class)
|
||||
{
|
||||
} else if (cs[i] == boolean.class || cs[i] == Boolean.class) {
|
||||
args[i] = Convert.toBool(args[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return (E) method.invoke(obj, args);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
|
||||
} catch (Exception e) {
|
||||
String msg = "method: " + method + ", obj: " + obj + ", args: " + Arrays.toString(args);
|
||||
throw convertReflectionExceptionToUnchecked(msg, e);
|
||||
}
|
||||
}
|
||||
|
|
@ -223,24 +177,18 @@ public class ReflectUtils
|
|||
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
*/
|
||||
public static Field getAccessibleField(final Object obj, final String fieldName)
|
||||
{
|
||||
public static Field getAccessibleField(final Object obj, final String fieldName) {
|
||||
// 为空不报错。直接返回 null
|
||||
if (obj == null)
|
||||
{
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
Validate.notBlank(fieldName, "fieldName can't be blank");
|
||||
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
|
||||
{
|
||||
try
|
||||
{
|
||||
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
|
||||
try {
|
||||
Field field = superClass.getDeclaredField(fieldName);
|
||||
makeAccessible(field);
|
||||
makeAccessible(field, obj);
|
||||
return field;
|
||||
}
|
||||
catch (NoSuchFieldException e)
|
||||
{
|
||||
} catch (NoSuchFieldException e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
@ -254,25 +202,18 @@ public class ReflectUtils
|
|||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethod(final Object obj, final String methodName,
|
||||
final Class<?>... parameterTypes)
|
||||
{
|
||||
final Class<?>... parameterTypes) {
|
||||
// 为空不报错。直接返回 null
|
||||
if (obj == null)
|
||||
{
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
|
||||
{
|
||||
try
|
||||
{
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
try {
|
||||
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
|
||||
makeAccessible(method);
|
||||
makeAccessible(method, obj);
|
||||
return method;
|
||||
}
|
||||
catch (NoSuchMethodException e)
|
||||
{
|
||||
continue;
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
|
@ -284,22 +225,17 @@ public class ReflectUtils
|
|||
* 只匹配函数名。
|
||||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
|
||||
{
|
||||
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) {
|
||||
// 为空不报错。直接返回 null
|
||||
if (obj == null)
|
||||
{
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
|
||||
{
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
Method[] methods = searchType.getDeclaredMethods();
|
||||
for (Method method : methods)
|
||||
{
|
||||
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
|
||||
{
|
||||
makeAccessible(method);
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) {
|
||||
makeAccessible(method, obj);
|
||||
return method;
|
||||
}
|
||||
}
|
||||
|
|
@ -310,11 +246,9 @@ public class ReflectUtils
|
|||
/**
|
||||
* 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Method method)
|
||||
{
|
||||
public static void makeAccessible(Method method, Object obj) {
|
||||
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
|
||||
&& !method.isAccessible())
|
||||
{
|
||||
&& !method.canAccess(obj)) {
|
||||
method.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -322,11 +256,9 @@ public class ReflectUtils
|
|||
/**
|
||||
* 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Field field)
|
||||
{
|
||||
public static void makeAccessible(Field field, Object obj) {
|
||||
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|
||||
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
|
||||
{
|
||||
|| Modifier.isFinal(field.getModifiers())) && !field.canAccess(obj)) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -336,8 +268,7 @@ public class ReflectUtils
|
|||
* 如无法找到, 返回Object.class.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<T> getClassGenricType(final Class clazz)
|
||||
{
|
||||
public static <T> Class<T> getClassGenricType(final Class clazz) {
|
||||
return getClassGenricType(clazz, 0);
|
||||
}
|
||||
|
||||
|
|
@ -345,26 +276,22 @@ public class ReflectUtils
|
|||
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
|
||||
* 如无法找到, 返回Object.class.
|
||||
*/
|
||||
public static Class getClassGenricType(final Class clazz, final int index)
|
||||
{
|
||||
public static Class getClassGenricType(final Class clazz, final int index) {
|
||||
Type genType = clazz.getGenericSuperclass();
|
||||
|
||||
if (!(genType instanceof ParameterizedType))
|
||||
{
|
||||
if (!(genType instanceof ParameterizedType)) {
|
||||
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
|
||||
|
||||
if (index >= params.length || index < 0)
|
||||
{
|
||||
if (index >= params.length || index < 0) {
|
||||
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
|
||||
+ params.length);
|
||||
return Object.class;
|
||||
}
|
||||
if (!(params[index] instanceof Class))
|
||||
{
|
||||
if (!(params[index] instanceof Class)) {
|
||||
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
|
||||
return Object.class;
|
||||
}
|
||||
|
|
@ -372,18 +299,14 @@ public class ReflectUtils
|
|||
return (Class) params[index];
|
||||
}
|
||||
|
||||
public static Class<?> getUserClass(Object instance)
|
||||
{
|
||||
if (instance == null)
|
||||
{
|
||||
public static Class<?> getUserClass(Object instance) {
|
||||
if (instance == null) {
|
||||
throw new RuntimeException("Instance must not be null");
|
||||
}
|
||||
Class clazz = instance.getClass();
|
||||
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR))
|
||||
{
|
||||
if (clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
|
||||
Class<?> superClass = clazz.getSuperclass();
|
||||
if (superClass != null && !Object.class.equals(superClass))
|
||||
{
|
||||
if (superClass != null && !Object.class.equals(superClass)) {
|
||||
return superClass;
|
||||
}
|
||||
}
|
||||
|
|
@ -394,15 +317,11 @@ public class ReflectUtils
|
|||
/**
|
||||
* 将反射时的checked exception转换为unchecked exception.
|
||||
*/
|
||||
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
|
||||
{
|
||||
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) {
|
||||
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|
||||
|| e instanceof NoSuchMethodException)
|
||||
{
|
||||
|| e instanceof NoSuchMethodException) {
|
||||
return new IllegalArgumentException(msg, e);
|
||||
}
|
||||
else if (e instanceof InvocationTargetException)
|
||||
{
|
||||
} else if (e instanceof InvocationTargetException) {
|
||||
return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
|
||||
}
|
||||
return new RuntimeException(msg, e);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.ruoyi.common.core.web.controller;
|
|||
import java.beans.PropertyEditorSupport;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
|
|
@ -16,25 +17,21 @@ import com.ruoyi.common.core.web.page.TableDataInfo;
|
|||
|
||||
/**
|
||||
* web层通用数据处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class BaseController
|
||||
{
|
||||
public class BaseController {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
/**
|
||||
* 将前台传递过来的日期格式的字符串,自动转化为Date类型
|
||||
*/
|
||||
@InitBinder
|
||||
public void initBinder(WebDataBinder binder)
|
||||
{
|
||||
public void initBinder(WebDataBinder binder) {
|
||||
// Date 类型转换
|
||||
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
|
||||
{
|
||||
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
|
||||
@Override
|
||||
public void setAsText(String text)
|
||||
{
|
||||
public void setAsText(String text) {
|
||||
setValue(DateUtils.parseDate(text));
|
||||
}
|
||||
});
|
||||
|
|
@ -43,25 +40,22 @@ public class BaseController
|
|||
/**
|
||||
* 设置请求分页数据
|
||||
*/
|
||||
protected void startPage()
|
||||
{
|
||||
protected void startPage() {
|
||||
PageUtils.startPage();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理分页的线程变量
|
||||
*/
|
||||
protected void clearPage()
|
||||
{
|
||||
protected void clearPage() {
|
||||
PageUtils.clearPage();
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应请求分页数据
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
protected TableDataInfo getDataTable(List<?> list)
|
||||
{
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
protected TableDataInfo getDataTable(List<?> list) {
|
||||
TableDataInfo rspData = new TableDataInfo();
|
||||
rspData.setCode(HttpStatus.SUCCESS);
|
||||
rspData.setRows(list);
|
||||
|
|
@ -73,70 +67,62 @@ public class BaseController
|
|||
/**
|
||||
* 返回成功
|
||||
*/
|
||||
public AjaxResult success()
|
||||
{
|
||||
public AjaxResult success() {
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功消息
|
||||
*/
|
||||
public AjaxResult success(String message)
|
||||
{
|
||||
public AjaxResult success(String message) {
|
||||
return AjaxResult.success(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功消息
|
||||
*/
|
||||
public AjaxResult success(Object data)
|
||||
{
|
||||
public AjaxResult success(Object data) {
|
||||
return AjaxResult.success(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败消息
|
||||
*/
|
||||
public AjaxResult error()
|
||||
{
|
||||
public AjaxResult error() {
|
||||
return AjaxResult.error();
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败消息
|
||||
*/
|
||||
public AjaxResult error(String message)
|
||||
{
|
||||
public AjaxResult error(String message) {
|
||||
return AjaxResult.error(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回警告消息
|
||||
*/
|
||||
public AjaxResult warn(String message)
|
||||
{
|
||||
public AjaxResult warn(String message) {
|
||||
return AjaxResult.warn(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应返回结果
|
||||
*
|
||||
*
|
||||
* @param rows 影响行数
|
||||
* @return 操作结果
|
||||
*/
|
||||
protected AjaxResult toAjax(int rows)
|
||||
{
|
||||
protected AjaxResult toAjax(int rows) {
|
||||
return rows > 0 ? AjaxResult.success() : AjaxResult.error();
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应返回结果
|
||||
*
|
||||
*
|
||||
* @param result 结果
|
||||
* @return 操作结果
|
||||
*/
|
||||
protected AjaxResult toAjax(boolean result)
|
||||
{
|
||||
protected AjaxResult toAjax(boolean result) {
|
||||
return result ? success() : error();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package com.ruoyi.common.core.xss;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package com.ruoyi.common.core.xss;
|
|||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.ruoyi.common.datascope.aspect;
|
|||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
|
|
@ -18,13 +19,12 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
|
||||
/**
|
||||
* 数据过滤处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class DataScopeAspect
|
||||
{
|
||||
public class DataScopeAspect {
|
||||
/**
|
||||
* 全部数据权限
|
||||
*/
|
||||
|
|
@ -56,22 +56,18 @@ public class DataScopeAspect
|
|||
public static final String DATA_SCOPE = "dataScope";
|
||||
|
||||
@Before("@annotation(controllerDataScope)")
|
||||
public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable
|
||||
{
|
||||
public void doBefore(JoinPoint point, DataScope controllerDataScope) {
|
||||
clearDataScope(point);
|
||||
handleDataScope(point, controllerDataScope);
|
||||
}
|
||||
|
||||
protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope)
|
||||
{
|
||||
protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
|
||||
// 获取当前的用户
|
||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
||||
if (StringUtils.isNotNull(loginUser))
|
||||
{
|
||||
if (StringUtils.isNotNull(loginUser)) {
|
||||
SysUser currentUser = loginUser.getSysUser();
|
||||
// 如果是超级管理员,则不过滤数据
|
||||
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
|
||||
{
|
||||
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
|
||||
String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), SecurityContextHolder.getPermission());
|
||||
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
|
||||
controllerDataScope.userAlias(), permission);
|
||||
|
|
@ -81,60 +77,44 @@ public class DataScopeAspect
|
|||
|
||||
/**
|
||||
* 数据范围过滤
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @param user 用户
|
||||
* @param deptAlias 部门别名
|
||||
* @param userAlias 用户别名
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @param user 用户
|
||||
* @param deptAlias 部门别名
|
||||
* @param userAlias 用户别名
|
||||
* @param permission 权限字符
|
||||
*/
|
||||
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission)
|
||||
{
|
||||
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission) {
|
||||
StringBuilder sqlString = new StringBuilder();
|
||||
List<String> conditions = new ArrayList<String>();
|
||||
|
||||
for (SysRole role : user.getRoles())
|
||||
{
|
||||
for (SysRole role : user.getRoles()) {
|
||||
String dataScope = role.getDataScope();
|
||||
if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope))
|
||||
{
|
||||
if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) {
|
||||
continue;
|
||||
}
|
||||
if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions())
|
||||
&& !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission)))
|
||||
{
|
||||
&& !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) {
|
||||
continue;
|
||||
}
|
||||
if (DATA_SCOPE_ALL.equals(dataScope))
|
||||
{
|
||||
if (DATA_SCOPE_ALL.equals(dataScope)) {
|
||||
sqlString = new StringBuilder();
|
||||
conditions.add(dataScope);
|
||||
break;
|
||||
}
|
||||
else if (DATA_SCOPE_CUSTOM.equals(dataScope))
|
||||
{
|
||||
} else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
|
||||
sqlString.append(StringUtils.format(
|
||||
" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
|
||||
role.getRoleId()));
|
||||
}
|
||||
else if (DATA_SCOPE_DEPT.equals(dataScope))
|
||||
{
|
||||
} else if (DATA_SCOPE_DEPT.equals(dataScope)) {
|
||||
sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
|
||||
}
|
||||
else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
|
||||
{
|
||||
} else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
|
||||
sqlString.append(StringUtils.format(
|
||||
" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
|
||||
deptAlias, user.getDeptId(), user.getDeptId()));
|
||||
}
|
||||
else if (DATA_SCOPE_SELF.equals(dataScope))
|
||||
{
|
||||
if (StringUtils.isNotBlank(userAlias))
|
||||
{
|
||||
} else if (DATA_SCOPE_SELF.equals(dataScope)) {
|
||||
if (StringUtils.isNotBlank(userAlias)) {
|
||||
sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
// 数据权限为仅本人且没有userAlias别名不查询任何数据
|
||||
sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
|
||||
}
|
||||
|
|
@ -143,17 +123,13 @@ public class DataScopeAspect
|
|||
}
|
||||
|
||||
// 多角色情况下,所有角色都不包含传递过来的权限字符,这个时候sqlString也会为空,所以要限制一下,不查询任何数据
|
||||
if (StringUtils.isEmpty(conditions))
|
||||
{
|
||||
if (StringUtils.isEmpty(conditions)) {
|
||||
sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(sqlString.toString()))
|
||||
{
|
||||
if (StringUtils.isNotBlank(sqlString.toString())) {
|
||||
Object params = joinPoint.getArgs()[0];
|
||||
if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
|
||||
{
|
||||
BaseEntity baseEntity = (BaseEntity) params;
|
||||
if (StringUtils.isNotNull(params) && params instanceof BaseEntity baseEntity) {
|
||||
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
|
||||
}
|
||||
}
|
||||
|
|
@ -162,12 +138,9 @@ public class DataScopeAspect
|
|||
/**
|
||||
* 拼接权限sql前先清空params.dataScope参数防止注入
|
||||
*/
|
||||
private void clearDataScope(final JoinPoint joinPoint)
|
||||
{
|
||||
private void clearDataScope(final JoinPoint joinPoint) {
|
||||
Object params = joinPoint.getArgs()[0];
|
||||
if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
|
||||
{
|
||||
BaseEntity baseEntity = (BaseEntity) params;
|
||||
if (StringUtils.isNotNull(params) && params instanceof BaseEntity baseEntity) {
|
||||
baseEntity.getParams().put(DATA_SCOPE, "");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,14 +20,15 @@
|
|||
<!-- Druid -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<artifactId>druid-spring-boot-3-starter</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Dynamic DataSource -->
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
|
||||
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
|
||||
<version>${dynamic-ds.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@ package com.ruoyi.common.log.aspect;
|
|||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
|
|
@ -31,19 +32,22 @@ import com.ruoyi.system.api.domain.SysOperLog;
|
|||
|
||||
/**
|
||||
* 操作日志记录处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class LogAspect
|
||||
{
|
||||
public class LogAspect {
|
||||
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
|
||||
|
||||
/** 排除敏感属性字段 */
|
||||
public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
|
||||
/**
|
||||
* 排除敏感属性字段
|
||||
*/
|
||||
public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};
|
||||
|
||||
/** 计算操作消耗时间 */
|
||||
/**
|
||||
* 计算操作消耗时间
|
||||
*/
|
||||
private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");
|
||||
|
||||
@Autowired
|
||||
|
|
@ -53,8 +57,7 @@ public class LogAspect
|
|||
* 处理请求前执行
|
||||
*/
|
||||
@Before(value = "@annotation(controllerLog)")
|
||||
public void boBefore(JoinPoint joinPoint, Log controllerLog)
|
||||
{
|
||||
public void boBefore(JoinPoint joinPoint, Log controllerLog) {
|
||||
TIME_THREADLOCAL.set(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
|
|
@ -64,27 +67,23 @@ public class LogAspect
|
|||
* @param joinPoint 切点
|
||||
*/
|
||||
@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
|
||||
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult)
|
||||
{
|
||||
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
|
||||
handleLog(joinPoint, controllerLog, null, jsonResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截异常操作
|
||||
*
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @param e 异常
|
||||
* @param e 异常
|
||||
*/
|
||||
@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
|
||||
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
|
||||
{
|
||||
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
|
||||
handleLog(joinPoint, controllerLog, e, null);
|
||||
}
|
||||
|
||||
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
|
||||
{
|
||||
try
|
||||
{
|
||||
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
|
||||
try {
|
||||
// *========数据库日志=========*//
|
||||
SysOperLog operLog = new SysOperLog();
|
||||
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
|
||||
|
|
@ -93,13 +92,11 @@ public class LogAspect
|
|||
operLog.setOperIp(ip);
|
||||
operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
|
||||
String username = SecurityUtils.getUsername();
|
||||
if (StringUtils.isNotBlank(username))
|
||||
{
|
||||
if (StringUtils.isNotBlank(username)) {
|
||||
operLog.setOperName(username);
|
||||
}
|
||||
|
||||
if (e != null)
|
||||
{
|
||||
if (e != null) {
|
||||
operLog.setStatus(BusinessStatus.FAIL.ordinal());
|
||||
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
|
||||
}
|
||||
|
|
@ -115,28 +112,22 @@ public class LogAspect
|
|||
operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
|
||||
// 保存数据库
|
||||
asyncLogService.saveSysLog(operLog);
|
||||
}
|
||||
catch (Exception exp)
|
||||
{
|
||||
} catch (Exception exp) {
|
||||
// 记录本地异常日志
|
||||
log.error("异常信息:{}", exp.getMessage());
|
||||
exp.printStackTrace();
|
||||
}
|
||||
finally
|
||||
{
|
||||
} finally {
|
||||
TIME_THREADLOCAL.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取注解中对方法的描述信息 用于Controller层注解
|
||||
*
|
||||
* @param log 日志
|
||||
*
|
||||
* @param log 日志
|
||||
* @param operLog 操作日志
|
||||
* @throws Exception
|
||||
*/
|
||||
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception
|
||||
{
|
||||
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception {
|
||||
// 设置action动作
|
||||
operLog.setBusinessType(log.businessType().ordinal());
|
||||
// 设置标题
|
||||
|
|
@ -144,36 +135,30 @@ public class LogAspect
|
|||
// 设置操作人类别
|
||||
operLog.setOperatorType(log.operatorType().ordinal());
|
||||
// 是否需要保存request,参数和值
|
||||
if (log.isSaveRequestData())
|
||||
{
|
||||
if (log.isSaveRequestData()) {
|
||||
// 获取参数的信息,传入到数据库中。
|
||||
setRequestValue(joinPoint, operLog, log.excludeParamNames());
|
||||
}
|
||||
// 是否需要保存response,参数和值
|
||||
if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
|
||||
{
|
||||
if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
|
||||
operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求的参数,放到log中
|
||||
*
|
||||
*
|
||||
* @param operLog 操作日志
|
||||
* @throws Exception 异常
|
||||
*/
|
||||
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception
|
||||
{
|
||||
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception {
|
||||
String requestMethod = operLog.getRequestMethod();
|
||||
Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
|
||||
if (StringUtils.isEmpty(paramsMap)
|
||||
&& (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)))
|
||||
{
|
||||
&& (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))) {
|
||||
String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);
|
||||
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000));
|
||||
}
|
||||
}
|
||||
|
|
@ -181,64 +166,48 @@ public class LogAspect
|
|||
/**
|
||||
* 参数拼装
|
||||
*/
|
||||
private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames)
|
||||
{
|
||||
String params = "";
|
||||
if (paramsArray != null && paramsArray.length > 0)
|
||||
{
|
||||
for (Object o : paramsArray)
|
||||
{
|
||||
if (StringUtils.isNotNull(o) && !isFilterObject(o))
|
||||
{
|
||||
try
|
||||
{
|
||||
private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) {
|
||||
StringBuilder params = new StringBuilder();
|
||||
if (paramsArray != null) {
|
||||
for (Object o : paramsArray) {
|
||||
if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
|
||||
try {
|
||||
String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames));
|
||||
params += jsonObj.toString() + " ";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
params.append(jsonObj).append(" ");
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return params.trim();
|
||||
return params.toString().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 忽略敏感属性
|
||||
*/
|
||||
public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames)
|
||||
{
|
||||
public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames) {
|
||||
return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否需要过滤的对象。
|
||||
*
|
||||
*
|
||||
* @param o 对象信息。
|
||||
* @return 如果是需要过滤的对象,则返回true;否则返回false。
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public boolean isFilterObject(final Object o)
|
||||
{
|
||||
public boolean isFilterObject(final Object o) {
|
||||
Class<?> clazz = o.getClass();
|
||||
if (clazz.isArray())
|
||||
{
|
||||
if (clazz.isArray()) {
|
||||
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
|
||||
}
|
||||
else if (Collection.class.isAssignableFrom(clazz))
|
||||
{
|
||||
} else if (Collection.class.isAssignableFrom(clazz)) {
|
||||
Collection collection = (Collection) o;
|
||||
for (Object value : collection)
|
||||
{
|
||||
for (Object value : collection) {
|
||||
return value instanceof MultipartFile;
|
||||
}
|
||||
}
|
||||
else if (Map.class.isAssignableFrom(clazz))
|
||||
{
|
||||
} else if (Map.class.isAssignableFrom(clazz)) {
|
||||
Map map = (Map) o;
|
||||
for (Object value : map.entrySet())
|
||||
{
|
||||
for (Object value : map.entrySet()) {
|
||||
Map.Entry entry = (Map.Entry) value;
|
||||
return entry.getValue() instanceof MultipartFile;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package com.ruoyi.common.redis.configure;
|
|||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.cache.annotation.CachingConfigurer;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
|
@ -18,7 +18,7 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
|
|||
@Configuration
|
||||
@EnableCaching
|
||||
@AutoConfigureBefore(RedisAutoConfiguration.class)
|
||||
public class RedisConfig extends CachingConfigurerSupport
|
||||
public class RedisConfig implements CachingConfigurer
|
||||
{
|
||||
@Bean
|
||||
@SuppressWarnings(value = { "unchecked", "rawtypes" })
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package com.ruoyi.common.security.annotation;
|
||||
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
|
|
@ -17,11 +19,15 @@ public @interface EnableRyFeignClients
|
|||
{
|
||||
String[] value() default {};
|
||||
|
||||
@AliasFor(annotation = EnableFeignClients.class)
|
||||
String[] basePackages() default { "com.ruoyi" };
|
||||
|
||||
@AliasFor(annotation = EnableFeignClients.class)
|
||||
Class<?>[] basePackageClasses() default {};
|
||||
|
||||
@AliasFor(annotation = EnableFeignClients.class)
|
||||
Class<?>[] defaultConfiguration() default {};
|
||||
|
||||
@AliasFor(annotation = EnableFeignClients.class)
|
||||
Class<?>[] clients() default {};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.common.security.feign;
|
||||
|
||||
import java.util.Map;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
|
|
@ -12,38 +13,31 @@ import feign.RequestTemplate;
|
|||
|
||||
/**
|
||||
* feign 请求拦截器
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class FeignRequestInterceptor implements RequestInterceptor
|
||||
{
|
||||
public class FeignRequestInterceptor implements RequestInterceptor {
|
||||
@Override
|
||||
public void apply(RequestTemplate requestTemplate)
|
||||
{
|
||||
public void apply(RequestTemplate requestTemplate) {
|
||||
HttpServletRequest httpServletRequest = ServletUtils.getRequest();
|
||||
if (StringUtils.isNotNull(httpServletRequest))
|
||||
{
|
||||
if (StringUtils.isNotNull(httpServletRequest)) {
|
||||
Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
|
||||
// 传递用户信息请求头,防止丢失
|
||||
String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
|
||||
if (StringUtils.isNotEmpty(userId))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(userId)) {
|
||||
requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
|
||||
}
|
||||
String userKey = headers.get(SecurityConstants.USER_KEY);
|
||||
if (StringUtils.isNotEmpty(userKey))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(userKey)) {
|
||||
requestTemplate.header(SecurityConstants.USER_KEY, userKey);
|
||||
}
|
||||
String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
|
||||
if (StringUtils.isNotEmpty(userName))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(userName)) {
|
||||
requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
|
||||
}
|
||||
String authentication = headers.get(SecurityConstants.AUTHORIZATION_HEADER);
|
||||
if (StringUtils.isNotEmpty(authentication))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(authentication)) {
|
||||
requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import org.springframework.web.bind.MissingPathVariableException;
|
|||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
|
|
@ -124,7 +124,7 @@ public class GlobalExceptionHandler
|
|||
public AjaxResult handleBindException(BindException e)
|
||||
{
|
||||
log.error(e.getMessage(), e);
|
||||
String message = e.getAllErrors().get(0).getDefaultMessage();
|
||||
String message = e.getAllErrors().getFirst().getDefaultMessage();
|
||||
return AjaxResult.error(message);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package com.ruoyi.common.security.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
|
|
@ -18,13 +18,10 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class HeaderInterceptor implements AsyncHandlerInterceptor
|
||||
{
|
||||
public class HeaderInterceptor implements AsyncHandlerInterceptor {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
|
||||
{
|
||||
if (!(handler instanceof HandlerMethod))
|
||||
{
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
if (!(handler instanceof HandlerMethod)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -33,11 +30,9 @@ public class HeaderInterceptor implements AsyncHandlerInterceptor
|
|||
SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
|
||||
|
||||
String token = SecurityUtils.getToken();
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token)) {
|
||||
LoginUser loginUser = AuthUtil.getLoginUser(token);
|
||||
if (StringUtils.isNotNull(loginUser))
|
||||
{
|
||||
if (StringUtils.isNotNull(loginUser)) {
|
||||
AuthUtil.verifyLoginUserExpire(loginUser);
|
||||
SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
|
||||
}
|
||||
|
|
@ -47,8 +42,7 @@ public class HeaderInterceptor implements AsyncHandlerInterceptor
|
|||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception
|
||||
{
|
||||
throws Exception {
|
||||
SecurityContextHolder.remove();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ package com.ruoyi.common.security.service;
|
|||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
|
@ -21,12 +22,11 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
|
||||
/**
|
||||
* token验证处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class TokenService
|
||||
{
|
||||
public class TokenService {
|
||||
private static final Logger log = LoggerFactory.getLogger(TokenService.class);
|
||||
|
||||
@Autowired
|
||||
|
|
@ -45,8 +45,7 @@ public class TokenService
|
|||
/**
|
||||
* 创建令牌
|
||||
*/
|
||||
public Map<String, Object> createToken(LoginUser loginUser)
|
||||
{
|
||||
public Map<String, Object> createToken(LoginUser loginUser) {
|
||||
String token = IdUtils.fastUUID();
|
||||
Long userId = loginUser.getSysUser().getUserId();
|
||||
String userName = loginUser.getSysUser().getUserName();
|
||||
|
|
@ -74,8 +73,7 @@ public class TokenService
|
|||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
public LoginUser getLoginUser()
|
||||
{
|
||||
public LoginUser getLoginUser() {
|
||||
return getLoginUser(ServletUtils.getRequest());
|
||||
}
|
||||
|
||||
|
|
@ -84,8 +82,7 @@ public class TokenService
|
|||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
public LoginUser getLoginUser(HttpServletRequest request)
|
||||
{
|
||||
public LoginUser getLoginUser(HttpServletRequest request) {
|
||||
// 获取请求携带的令牌
|
||||
String token = SecurityUtils.getToken(request);
|
||||
return getLoginUser(token);
|
||||
|
|
@ -96,20 +93,15 @@ public class TokenService
|
|||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
public LoginUser getLoginUser(String token)
|
||||
{
|
||||
public LoginUser getLoginUser(String token) {
|
||||
LoginUser user = null;
|
||||
try
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
try {
|
||||
if (StringUtils.isNotEmpty(token)) {
|
||||
String userkey = JwtUtils.getUserKey(token);
|
||||
user = redisService.getCacheObject(getTokenKey(userkey));
|
||||
return user;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
log.error("获取用户信息异常'{}'", e.getMessage());
|
||||
}
|
||||
return user;
|
||||
|
|
@ -118,10 +110,8 @@ public class TokenService
|
|||
/**
|
||||
* 设置用户身份信息
|
||||
*/
|
||||
public void setLoginUser(LoginUser loginUser)
|
||||
{
|
||||
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
|
||||
{
|
||||
public void setLoginUser(LoginUser loginUser) {
|
||||
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
|
||||
refreshToken(loginUser);
|
||||
}
|
||||
}
|
||||
|
|
@ -129,10 +119,8 @@ public class TokenService
|
|||
/**
|
||||
* 删除用户缓存信息
|
||||
*/
|
||||
public void delLoginUser(String token)
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
public void delLoginUser(String token) {
|
||||
if (StringUtils.isNotEmpty(token)) {
|
||||
String userkey = JwtUtils.getUserKey(token);
|
||||
redisService.deleteObject(getTokenKey(userkey));
|
||||
}
|
||||
|
|
@ -140,15 +128,11 @@ public class TokenService
|
|||
|
||||
/**
|
||||
* 验证令牌有效期,相差不足120分钟,自动刷新缓存
|
||||
*
|
||||
* @param loginUser
|
||||
*/
|
||||
public void verifyToken(LoginUser loginUser)
|
||||
{
|
||||
public void verifyToken(LoginUser loginUser) {
|
||||
long expireTime = loginUser.getExpireTime();
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
|
||||
{
|
||||
if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
|
||||
refreshToken(loginUser);
|
||||
}
|
||||
}
|
||||
|
|
@ -158,8 +142,7 @@ public class TokenService
|
|||
*
|
||||
* @param loginUser 登录信息
|
||||
*/
|
||||
public void refreshToken(LoginUser loginUser)
|
||||
{
|
||||
public void refreshToken(LoginUser loginUser) {
|
||||
loginUser.setLoginTime(System.currentTimeMillis());
|
||||
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
|
||||
// 根据uuid将loginUser缓存
|
||||
|
|
@ -167,8 +150,7 @@ public class TokenService
|
|||
redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
private String getTokenKey(String token)
|
||||
{
|
||||
private String getTokenKey(String token) {
|
||||
return ACCESS_TOKEN + token;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
package com.ruoyi.common.security.utils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.constant.TokenConstants;
|
||||
|
|
@ -11,56 +11,49 @@ import com.ruoyi.system.api.model.LoginUser;
|
|||
|
||||
/**
|
||||
* 权限获取工具类
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SecurityUtils
|
||||
{
|
||||
public class SecurityUtils {
|
||||
/**
|
||||
* 获取用户ID
|
||||
*/
|
||||
public static Long getUserId()
|
||||
{
|
||||
public static Long getUserId() {
|
||||
return SecurityContextHolder.getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户名称
|
||||
*/
|
||||
public static String getUsername()
|
||||
{
|
||||
public static String getUsername() {
|
||||
return SecurityContextHolder.getUserName();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户key
|
||||
*/
|
||||
public static String getUserKey()
|
||||
{
|
||||
public static String getUserKey() {
|
||||
return SecurityContextHolder.getUserKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录用户信息
|
||||
*/
|
||||
public static LoginUser getLoginUser()
|
||||
{
|
||||
public static LoginUser getLoginUser() {
|
||||
return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求token
|
||||
*/
|
||||
public static String getToken()
|
||||
{
|
||||
public static String getToken() {
|
||||
return getToken(ServletUtils.getRequest());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据request获取请求token
|
||||
*/
|
||||
public static String getToken(HttpServletRequest request)
|
||||
{
|
||||
public static String getToken(HttpServletRequest request) {
|
||||
// 从header获取token标识
|
||||
String token = request.getHeader(TokenConstants.AUTHENTICATION);
|
||||
return replaceTokenPrefix(token);
|
||||
|
|
@ -69,11 +62,9 @@ public class SecurityUtils
|
|||
/**
|
||||
* 裁剪token前缀
|
||||
*/
|
||||
public static String replaceTokenPrefix(String token)
|
||||
{
|
||||
public static String replaceTokenPrefix(String token) {
|
||||
// 如果前端设置了令牌前缀,则裁剪掉前缀
|
||||
if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
|
||||
token = token.replaceFirst(TokenConstants.PREFIX, "");
|
||||
}
|
||||
return token;
|
||||
|
|
@ -81,12 +72,11 @@ public class SecurityUtils
|
|||
|
||||
/**
|
||||
* 是否为管理员
|
||||
*
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean isAdmin(Long userId)
|
||||
{
|
||||
public static boolean isAdmin(Long userId) {
|
||||
return userId != null && 1L == userId;
|
||||
}
|
||||
|
||||
|
|
@ -96,8 +86,7 @@ public class SecurityUtils
|
|||
* @param password 密码
|
||||
* @return 加密字符串
|
||||
*/
|
||||
public static String encryptPassword(String password)
|
||||
{
|
||||
public static String encryptPassword(String password) {
|
||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
return passwordEncoder.encode(password);
|
||||
}
|
||||
|
|
@ -105,12 +94,11 @@ public class SecurityUtils
|
|||
/**
|
||||
* 判断密码是否相同
|
||||
*
|
||||
* @param rawPassword 真实密码
|
||||
* @param rawPassword 真实密码
|
||||
* @param encodedPassword 加密后字符
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean matchesPassword(String rawPassword, String encodedPassword)
|
||||
{
|
||||
public static boolean matchesPassword(String rawPassword, String encodedPassword) {
|
||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
return passwordEncoder.matches(rawPassword, encodedPassword);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,10 +24,14 @@
|
|||
</dependency>
|
||||
|
||||
<!-- Swagger -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger2</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
|
|
|||
|
|
@ -9,115 +9,115 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
|||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.ApiKey;
|
||||
import springfox.documentation.service.AuthorizationScope;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.service.SecurityReference;
|
||||
import springfox.documentation.service.SecurityScheme;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
//import springfox.documentation.builders.ApiInfoBuilder;
|
||||
//import springfox.documentation.builders.PathSelectors;
|
||||
//import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
//import springfox.documentation.service.ApiInfo;
|
||||
//import springfox.documentation.service.ApiKey;
|
||||
//import springfox.documentation.service.AuthorizationScope;
|
||||
//import springfox.documentation.service.Contact;
|
||||
//import springfox.documentation.service.SecurityReference;
|
||||
//import springfox.documentation.service.SecurityScheme;
|
||||
//import springfox.documentation.spi.DocumentationType;
|
||||
//import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
//import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
|
||||
//import springfox.documentation.spring.web.plugins.Docket;
|
||||
//import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
@EnableConfigurationProperties(SwaggerProperties.class)
|
||||
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
|
||||
@Import({SwaggerBeanPostProcessor.class, SwaggerWebConfiguration.class})
|
||||
//@Configuration
|
||||
//@EnableSwagger2
|
||||
//@EnableConfigurationProperties(SwaggerProperties.class)
|
||||
//@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
|
||||
//@Import({SwaggerBeanPostProcessor.class, SwaggerWebConfiguration.class})
|
||||
public class SwaggerAutoConfiguration
|
||||
{
|
||||
/**
|
||||
* 默认的排除路径,排除Spring Boot默认的错误处理路径和端点
|
||||
*/
|
||||
private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");
|
||||
|
||||
private static final String BASE_PATH = "/**";
|
||||
|
||||
@Bean
|
||||
public Docket api(SwaggerProperties swaggerProperties)
|
||||
{
|
||||
// base-path处理
|
||||
if (swaggerProperties.getBasePath().isEmpty())
|
||||
{
|
||||
swaggerProperties.getBasePath().add(BASE_PATH);
|
||||
}
|
||||
// noinspection unchecked
|
||||
List<Predicate<String>> basePath = new ArrayList<Predicate<String>>();
|
||||
swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));
|
||||
|
||||
// exclude-path处理
|
||||
if (swaggerProperties.getExcludePath().isEmpty())
|
||||
{
|
||||
swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
|
||||
}
|
||||
|
||||
List<Predicate<String>> excludePath = new ArrayList<>();
|
||||
swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
|
||||
|
||||
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
|
||||
.apiInfo(apiInfo(swaggerProperties)).select()
|
||||
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()));
|
||||
|
||||
swaggerProperties.getBasePath().forEach(p -> builder.paths(PathSelectors.ant(p)));
|
||||
swaggerProperties.getExcludePath().forEach(p -> builder.paths(PathSelectors.ant(p).negate()));
|
||||
|
||||
return builder.build().securitySchemes(securitySchemes()).securityContexts(securityContexts()).pathMapping("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全模式,这里指定token通过Authorization头请求头传递
|
||||
*/
|
||||
private List<SecurityScheme> securitySchemes()
|
||||
{
|
||||
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
|
||||
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
|
||||
return apiKeyList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全上下文
|
||||
*/
|
||||
private List<SecurityContext> securityContexts()
|
||||
{
|
||||
List<SecurityContext> securityContexts = new ArrayList<>();
|
||||
securityContexts.add(
|
||||
SecurityContext.builder()
|
||||
.securityReferences(defaultAuth())
|
||||
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
|
||||
.build());
|
||||
return securityContexts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认的全局鉴权策略
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private List<SecurityReference> defaultAuth()
|
||||
{
|
||||
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
|
||||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||
authorizationScopes[0] = authorizationScope;
|
||||
List<SecurityReference> securityReferences = new ArrayList<>();
|
||||
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
|
||||
return securityReferences;
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo(SwaggerProperties swaggerProperties)
|
||||
{
|
||||
return new ApiInfoBuilder()
|
||||
.title(swaggerProperties.getTitle())
|
||||
.description(swaggerProperties.getDescription())
|
||||
.license(swaggerProperties.getLicense())
|
||||
.licenseUrl(swaggerProperties.getLicenseUrl())
|
||||
.termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
|
||||
.contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
|
||||
.version(swaggerProperties.getVersion())
|
||||
.build();
|
||||
}
|
||||
// private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");
|
||||
//
|
||||
// private static final String BASE_PATH = "/**";
|
||||
//
|
||||
// @Bean
|
||||
// public Docket api(SwaggerProperties swaggerProperties)
|
||||
// {
|
||||
// // base-path处理
|
||||
// if (swaggerProperties.getBasePath().isEmpty())
|
||||
// {
|
||||
// swaggerProperties.getBasePath().add(BASE_PATH);
|
||||
// }
|
||||
// // noinspection unchecked
|
||||
// List<Predicate<String>> basePath = new ArrayList<Predicate<String>>();
|
||||
// swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));
|
||||
//
|
||||
// // exclude-path处理
|
||||
// if (swaggerProperties.getExcludePath().isEmpty())
|
||||
// {
|
||||
// swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
|
||||
// }
|
||||
//
|
||||
// List<Predicate<String>> excludePath = new ArrayList<>();
|
||||
// swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
|
||||
//
|
||||
// ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
|
||||
// .apiInfo(apiInfo(swaggerProperties)).select()
|
||||
// .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()));
|
||||
//
|
||||
// swaggerProperties.getBasePath().forEach(p -> builder.paths(PathSelectors.ant(p)));
|
||||
// swaggerProperties.getExcludePath().forEach(p -> builder.paths(PathSelectors.ant(p).negate()));
|
||||
//
|
||||
// return builder.build().securitySchemes(securitySchemes()).securityContexts(securityContexts()).pathMapping("/");
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 安全模式,这里指定token通过Authorization头请求头传递
|
||||
// */
|
||||
// private List<SecurityScheme> securitySchemes()
|
||||
// {
|
||||
// List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
|
||||
// apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
|
||||
// return apiKeyList;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 安全上下文
|
||||
// */
|
||||
// private List<SecurityContext> securityContexts()
|
||||
// {
|
||||
// List<SecurityContext> securityContexts = new ArrayList<>();
|
||||
// securityContexts.add(
|
||||
// SecurityContext.builder()
|
||||
// .securityReferences(defaultAuth())
|
||||
// .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
|
||||
// .build());
|
||||
// return securityContexts;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 默认的全局鉴权策略
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// private List<SecurityReference> defaultAuth()
|
||||
// {
|
||||
// AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
|
||||
// AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||
// authorizationScopes[0] = authorizationScope;
|
||||
// List<SecurityReference> securityReferences = new ArrayList<>();
|
||||
// securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
|
||||
// return securityReferences;
|
||||
// }
|
||||
//
|
||||
// private ApiInfo apiInfo(SwaggerProperties swaggerProperties)
|
||||
// {
|
||||
// return new ApiInfoBuilder()
|
||||
// .title(swaggerProperties.getTitle())
|
||||
// .description(swaggerProperties.getDescription())
|
||||
// .license(swaggerProperties.getLicense())
|
||||
// .licenseUrl(swaggerProperties.getLicenseUrl())
|
||||
// .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
|
||||
// .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
|
||||
// .version(swaggerProperties.getVersion())
|
||||
// .build();
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import org.springframework.beans.BeansException;
|
|||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
|
||||
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
|
||||
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
|
||||
//import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
|
||||
//import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
|
@ -17,36 +17,36 @@ import java.util.stream.Collectors;
|
|||
*/
|
||||
public class SwaggerBeanPostProcessor implements BeanPostProcessor
|
||||
{
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
|
||||
{
|
||||
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider)
|
||||
{
|
||||
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings)
|
||||
{
|
||||
List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
|
||||
.collect(Collectors.toList());
|
||||
mappings.clear();
|
||||
mappings.addAll(copy);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean)
|
||||
{
|
||||
try
|
||||
{
|
||||
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
|
||||
field.setAccessible(true);
|
||||
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
|
||||
}
|
||||
catch (IllegalArgumentException | IllegalAccessException e)
|
||||
{
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
// @Override
|
||||
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
|
||||
// {
|
||||
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider)
|
||||
// {
|
||||
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
|
||||
// }
|
||||
// return bean;
|
||||
// }
|
||||
//
|
||||
// private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings)
|
||||
// {
|
||||
// List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
|
||||
// .collect(Collectors.toList());
|
||||
// mappings.clear();
|
||||
// mappings.addAll(copy);
|
||||
// }
|
||||
//
|
||||
// @SuppressWarnings("unchecked")
|
||||
// private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
|
||||
// field.setAccessible(true);
|
||||
// return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
|
||||
// }
|
||||
// catch (IllegalArgumentException | IllegalAccessException e)
|
||||
// {
|
||||
// throw new IllegalStateException(e);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,12 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Nacos Config -->
|
||||
<dependency>
|
||||
|
|
@ -77,16 +83,20 @@
|
|||
</dependency>
|
||||
|
||||
<!-- Swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
</dependency>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger2</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springdoc</groupId>-->
|
||||
<!-- <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
|
|
|||
|
|
@ -6,24 +6,15 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
|||
|
||||
/**
|
||||
* 网关启动程序
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
|
||||
public class RuoYiGatewayApplication
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
|
||||
public class RuoYiGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RuoYiGatewayApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 若依网关启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 网关模块启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,23 @@
|
|||
package com.ruoyi.gateway.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import com.google.code.kaptcha.impl.DefaultKaptcha;
|
||||
import com.google.code.kaptcha.util.Config;
|
||||
|
||||
import static com.google.code.kaptcha.Constants.*;
|
||||
|
||||
/**
|
||||
* 验证码配置
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
public class CaptchaConfig
|
||||
{
|
||||
public class CaptchaConfig {
|
||||
@Bean(name = "captchaProducer")
|
||||
public DefaultKaptcha getKaptchaBean()
|
||||
{
|
||||
public DefaultKaptcha getKaptchaBean() {
|
||||
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
|
||||
Properties properties = new Properties();
|
||||
// 是否有边框 默认为true 我们可以自己设置yes,no
|
||||
|
|
@ -42,10 +42,9 @@ public class CaptchaConfig
|
|||
defaultKaptcha.setConfig(config);
|
||||
return defaultKaptcha;
|
||||
}
|
||||
|
||||
|
||||
@Bean(name = "captchaProducerMath")
|
||||
public DefaultKaptcha getKaptchaBeanMath()
|
||||
{
|
||||
public DefaultKaptcha getKaptchaBeanMath() {
|
||||
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
|
||||
Properties properties = new Properties();
|
||||
// 是否有边框 默认为true 我们可以自己设置yes,no
|
||||
|
|
|
|||
|
|
@ -8,16 +8,14 @@ import com.ruoyi.gateway.handler.SentinelFallbackHandler;
|
|||
|
||||
/**
|
||||
* 网关限流配置
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
public class GatewayConfig
|
||||
{
|
||||
public class GatewayConfig {
|
||||
@Bean
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public SentinelFallbackHandler sentinelGatewayExceptionHandler()
|
||||
{
|
||||
public SentinelFallbackHandler sentinelGatewayExceptionHandler() {
|
||||
return new SentinelFallbackHandler();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,75 +1,61 @@
|
|||
package com.ruoyi.gateway.config;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import com.google.code.kaptcha.text.impl.DefaultTextCreator;
|
||||
|
||||
/**
|
||||
* 验证码文本生成器
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class KaptchaTextCreator extends DefaultTextCreator
|
||||
{
|
||||
public class KaptchaTextCreator extends DefaultTextCreator {
|
||||
private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
|
||||
|
||||
@Override
|
||||
public String getText()
|
||||
{
|
||||
Integer result = 0;
|
||||
public String getText() {
|
||||
int result;
|
||||
Random random = new Random();
|
||||
int x = random.nextInt(10);
|
||||
int y = random.nextInt(10);
|
||||
StringBuilder suChinese = new StringBuilder();
|
||||
int randomoperands = random.nextInt(3);
|
||||
if (randomoperands == 0)
|
||||
{
|
||||
int randomOperands = random.nextInt(3);
|
||||
if (randomOperands == 0) {
|
||||
result = x * y;
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
suChinese.append("*");
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
}
|
||||
else if (randomoperands == 1)
|
||||
{
|
||||
if ((x != 0) && y % x == 0)
|
||||
{
|
||||
} else if (randomOperands == 1) {
|
||||
if ((x != 0) && y % x == 0) {
|
||||
result = y / x;
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
suChinese.append("/");
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
result = x + y;
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
suChinese.append("+");
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
}
|
||||
}
|
||||
else if (randomoperands == 2)
|
||||
{
|
||||
if (x >= y)
|
||||
{
|
||||
} else if (randomOperands == 2) {
|
||||
if (x >= y) {
|
||||
result = x - y;
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
suChinese.append("-");
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
result = y - x;
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
suChinese.append("-");
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
result = x + y;
|
||||
suChinese.append(CNUMBERS[x]);
|
||||
suChinese.append("+");
|
||||
suChinese.append(CNUMBERS[y]);
|
||||
}
|
||||
suChinese.append("=?@" + result);
|
||||
suChinese.append("=?@").append(result);
|
||||
return suChinese.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -11,19 +11,17 @@ import com.ruoyi.gateway.handler.ValidateCodeHandler;
|
|||
|
||||
/**
|
||||
* 路由配置信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
public class RouterFunctionConfiguration
|
||||
{
|
||||
public class RouterFunctionConfiguration {
|
||||
@Autowired
|
||||
private ValidateCodeHandler validateCodeHandler;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Bean
|
||||
public RouterFunction routerFunction()
|
||||
{
|
||||
public RouterFunction routerFunction() {
|
||||
return RouterFunctions.route(
|
||||
RequestPredicates.GET("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
|
||||
validateCodeHandler);
|
||||
|
|
|
|||
|
|
@ -10,70 +10,71 @@ import org.springframework.context.annotation.Lazy;
|
|||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
|
||||
import org.springframework.web.reactive.config.WebFluxConfigurer;
|
||||
import springfox.documentation.swagger.web.SwaggerResource;
|
||||
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
|
||||
//import springfox.documentation.swagger.web.SwaggerResource;
|
||||
//import springfox.documentation.swagger.web.SwaggerResourcesProvider;
|
||||
|
||||
/**
|
||||
* 聚合系统接口
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class SwaggerProvider implements SwaggerResourcesProvider, WebFluxConfigurer
|
||||
//@Component
|
||||
public class SwaggerProvider implements WebFluxConfigurer
|
||||
// ,SwaggerResourcesProvider
|
||||
{
|
||||
/**
|
||||
* Swagger2默认的url后缀
|
||||
*/
|
||||
public static final String SWAGGER2URL = "/v2/api-docs";
|
||||
|
||||
/**
|
||||
* 网关路由
|
||||
*/
|
||||
@Lazy
|
||||
@Autowired
|
||||
private RouteLocator routeLocator;
|
||||
|
||||
@Autowired
|
||||
private GatewayProperties gatewayProperties;
|
||||
|
||||
/**
|
||||
* 聚合其他服务接口
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<SwaggerResource> get()
|
||||
{
|
||||
List<SwaggerResource> resourceList = new ArrayList<>();
|
||||
List<String> routes = new ArrayList<>();
|
||||
// 获取网关中配置的route
|
||||
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
|
||||
gatewayProperties.getRoutes().stream()
|
||||
.filter(routeDefinition -> routes
|
||||
.contains(routeDefinition.getId()))
|
||||
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
||||
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
|
||||
.filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
||||
.forEach(predicateDefinition -> resourceList
|
||||
.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
|
||||
.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
|
||||
return resourceList;
|
||||
}
|
||||
|
||||
private SwaggerResource swaggerResource(String name, String location)
|
||||
{
|
||||
SwaggerResource swaggerResource = new SwaggerResource();
|
||||
swaggerResource.setName(name);
|
||||
swaggerResource.setLocation(location);
|
||||
swaggerResource.setSwaggerVersion("2.0");
|
||||
return swaggerResource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry)
|
||||
{
|
||||
/** swagger-ui 地址 */
|
||||
registry.addResourceHandler("/swagger-ui/**")
|
||||
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
|
||||
}
|
||||
// public static final String SWAGGER2URL = "/v2/api-docs";
|
||||
//
|
||||
// /**
|
||||
// * 网关路由
|
||||
// */
|
||||
// @Lazy
|
||||
// @Autowired
|
||||
// private RouteLocator routeLocator;
|
||||
//
|
||||
// @Autowired
|
||||
// private GatewayProperties gatewayProperties;
|
||||
//
|
||||
// /**
|
||||
// * 聚合其他服务接口
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// @Override
|
||||
// public List<SwaggerResource> get()
|
||||
// {
|
||||
// List<SwaggerResource> resourceList = new ArrayList<>();
|
||||
// List<String> routes = new ArrayList<>();
|
||||
// // 获取网关中配置的route
|
||||
// routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
|
||||
// gatewayProperties.getRoutes().stream()
|
||||
// .filter(routeDefinition -> routes
|
||||
// .contains(routeDefinition.getId()))
|
||||
// .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
||||
// .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
|
||||
// .filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
||||
// .forEach(predicateDefinition -> resourceList
|
||||
// .add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
|
||||
// .get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
|
||||
// return resourceList;
|
||||
// }
|
||||
//
|
||||
// private SwaggerResource swaggerResource(String name, String location)
|
||||
// {
|
||||
// SwaggerResource swaggerResource = new SwaggerResource();
|
||||
// swaggerResource.setName(name);
|
||||
// swaggerResource.setLocation(location);
|
||||
// swaggerResource.setSwaggerVersion("2.0");
|
||||
// return swaggerResource;
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void addResourceHandlers(ResourceHandlerRegistry registry)
|
||||
// {
|
||||
// /** swagger-ui 地址 */
|
||||
// registry.addResourceHandler("/swagger-ui/**")
|
||||
// .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,12 +23,11 @@ import reactor.core.publisher.Mono;
|
|||
|
||||
/**
|
||||
* 网关鉴权
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class AuthFilter implements GlobalFilter, Ordered
|
||||
{
|
||||
public class AuthFilter implements GlobalFilter, Ordered {
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
|
||||
|
||||
// 排除过滤的 uri 地址,nacos自行添加
|
||||
|
|
@ -40,37 +39,31 @@ public class AuthFilter implements GlobalFilter, Ordered
|
|||
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
|
||||
{
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
ServerHttpRequest.Builder mutate = request.mutate();
|
||||
|
||||
String url = request.getURI().getPath();
|
||||
// 跳过不需要验证的路径
|
||||
if (StringUtils.matches(url, ignoreWhite.getWhites()))
|
||||
{
|
||||
if (StringUtils.matches(url, ignoreWhite.getWhites())) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
String token = getToken(request);
|
||||
if (StringUtils.isEmpty(token))
|
||||
{
|
||||
if (StringUtils.isEmpty(token)) {
|
||||
return unauthorizedResponse(exchange, "令牌不能为空");
|
||||
}
|
||||
Claims claims = JwtUtils.parseToken(token);
|
||||
if (claims == null)
|
||||
{
|
||||
if (claims == null) {
|
||||
return unauthorizedResponse(exchange, "令牌已过期或验证不正确!");
|
||||
}
|
||||
String userkey = JwtUtils.getUserKey(claims);
|
||||
boolean islogin = redisService.hasKey(getTokenKey(userkey));
|
||||
if (!islogin)
|
||||
{
|
||||
if (!islogin) {
|
||||
return unauthorizedResponse(exchange, "登录状态已过期");
|
||||
}
|
||||
String userid = JwtUtils.getUserId(claims);
|
||||
String username = JwtUtils.getUserName(claims);
|
||||
if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username))
|
||||
{
|
||||
if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
|
||||
return unauthorizedResponse(exchange, "令牌验证失败");
|
||||
}
|
||||
|
||||
|
|
@ -83,10 +76,8 @@ public class AuthFilter implements GlobalFilter, Ordered
|
|||
return chain.filter(exchange.mutate().request(mutate.build()).build());
|
||||
}
|
||||
|
||||
private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
String valueStr = value.toString();
|
||||
|
|
@ -94,13 +85,11 @@ public class AuthFilter implements GlobalFilter, Ordered
|
|||
mutate.header(name, valueEncode);
|
||||
}
|
||||
|
||||
private void removeHeader(ServerHttpRequest.Builder mutate, String name)
|
||||
{
|
||||
private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
|
||||
mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
|
||||
}
|
||||
|
||||
private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
|
||||
{
|
||||
private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
|
||||
log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
|
||||
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
|
@ -108,28 +97,24 @@ public class AuthFilter implements GlobalFilter, Ordered
|
|||
/**
|
||||
* 获取缓存key
|
||||
*/
|
||||
private String getTokenKey(String token)
|
||||
{
|
||||
private String getTokenKey(String token) {
|
||||
return CacheConstants.LOGIN_TOKEN_KEY + token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求token
|
||||
*/
|
||||
private String getToken(ServerHttpRequest request)
|
||||
{
|
||||
private String getToken(ServerHttpRequest request) {
|
||||
String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
|
||||
// 如果前端设置了令牌前缀,则裁剪掉前缀
|
||||
if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
|
||||
token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder()
|
||||
{
|
||||
public int getOrder() {
|
||||
return -200;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ package com.ruoyi.gateway.filter;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
|
@ -10,20 +11,17 @@ import com.ruoyi.common.core.utils.ServletUtils;
|
|||
|
||||
/**
|
||||
* 黑名单过滤器
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config>
|
||||
{
|
||||
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {
|
||||
@Override
|
||||
public GatewayFilter apply(Config config)
|
||||
{
|
||||
public GatewayFilter apply(Config config) {
|
||||
return (exchange, chain) -> {
|
||||
|
||||
String url = exchange.getRequest().getURI().getPath();
|
||||
if (config.matchBlacklist(url))
|
||||
{
|
||||
if (config.matchBlacklist(url)) {
|
||||
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求地址不允许访问");
|
||||
}
|
||||
|
||||
|
|
@ -31,29 +29,24 @@ public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUr
|
|||
};
|
||||
}
|
||||
|
||||
public BlackListUrlFilter()
|
||||
{
|
||||
public BlackListUrlFilter() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
public static class Config
|
||||
{
|
||||
public static class Config {
|
||||
private List<String> blacklistUrl;
|
||||
|
||||
private List<Pattern> blacklistUrlPattern = new ArrayList<>();
|
||||
private final List<Pattern> blacklistUrlPattern = new ArrayList<>();
|
||||
|
||||
public boolean matchBlacklist(String url)
|
||||
{
|
||||
public boolean matchBlacklist(String url) {
|
||||
return !blacklistUrlPattern.isEmpty() && blacklistUrlPattern.stream().anyMatch(p -> p.matcher(url).find());
|
||||
}
|
||||
|
||||
public List<String> getBlacklistUrl()
|
||||
{
|
||||
public List<String> getBlacklistUrl() {
|
||||
return blacklistUrl;
|
||||
}
|
||||
|
||||
public void setBlacklistUrl(List<String> blacklistUrl)
|
||||
{
|
||||
public void setBlacklistUrl(List<String> blacklistUrl) {
|
||||
this.blacklistUrl = blacklistUrl;
|
||||
this.blacklistUrlPattern.clear();
|
||||
this.blacklistUrl.forEach(url -> {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.ruoyi.gateway.filter;
|
|||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
|
||||
|
|
@ -14,49 +15,40 @@ import reactor.core.publisher.Mono;
|
|||
|
||||
/**
|
||||
* 获取body请求数据(解决流不能重复读取问题)
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheRequestFilter.Config>
|
||||
{
|
||||
public CacheRequestFilter()
|
||||
{
|
||||
public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheRequestFilter.Config> {
|
||||
public CacheRequestFilter() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name()
|
||||
{
|
||||
public String name() {
|
||||
return "CacheRequestFilter";
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config)
|
||||
{
|
||||
public GatewayFilter apply(Config config) {
|
||||
CacheRequestGatewayFilter cacheRequestGatewayFilter = new CacheRequestGatewayFilter();
|
||||
Integer order = config.getOrder();
|
||||
if (order == null)
|
||||
{
|
||||
if (order == null) {
|
||||
return cacheRequestGatewayFilter;
|
||||
}
|
||||
return new OrderedGatewayFilter(cacheRequestGatewayFilter, order);
|
||||
}
|
||||
|
||||
public static class CacheRequestGatewayFilter implements GatewayFilter
|
||||
{
|
||||
public static class CacheRequestGatewayFilter implements GatewayFilter {
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
|
||||
{
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
// GET DELETE 不过滤
|
||||
HttpMethod method = exchange.getRequest().getMethod();
|
||||
if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE)
|
||||
{
|
||||
if (method == HttpMethod.GET || method == HttpMethod.DELETE) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
return ServerWebExchangeUtils.cacheRequestBodyAndRequest(exchange, (serverHttpRequest) -> {
|
||||
if (serverHttpRequest == exchange.getRequest())
|
||||
{
|
||||
if (serverHttpRequest == exchange.getRequest()) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
return chain.filter(exchange.mutate().request(serverHttpRequest).build());
|
||||
|
|
@ -65,22 +57,18 @@ public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheReques
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder()
|
||||
{
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Collections.singletonList("order");
|
||||
}
|
||||
|
||||
static class Config
|
||||
{
|
||||
static class Config {
|
||||
private Integer order;
|
||||
|
||||
public Integer getOrder()
|
||||
{
|
||||
public Integer getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Integer order)
|
||||
{
|
||||
public void setOrder(Integer order) {
|
||||
this.order = order;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.ruoyi.gateway.filter;
|
|||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
|
|
@ -24,9 +25,8 @@ import reactor.core.publisher.Flux;
|
|||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
||||
{
|
||||
private final static String[] VALIDATE_URL = new String[] { "/auth/login", "/auth/register" };
|
||||
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
|
||||
private final static String[] VALIDATE_URL = new String[]{"/auth/login", "/auth/register"};
|
||||
|
||||
@Autowired
|
||||
private ValidateCodeService validateCodeService;
|
||||
|
|
@ -39,33 +39,27 @@ public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
|||
private static final String UUID = "uuid";
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Object config)
|
||||
{
|
||||
public GatewayFilter apply(Object config) {
|
||||
return (exchange, chain) -> {
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
|
||||
// 非登录/注册请求或验证码关闭,不处理
|
||||
if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled())
|
||||
{
|
||||
if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled()) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
String rspStr = resolveBodyFromRequest(request);
|
||||
JSONObject obj = JSON.parseObject(rspStr);
|
||||
validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
|
||||
}
|
||||
return chain.filter(exchange);
|
||||
};
|
||||
}
|
||||
|
||||
private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
|
||||
{
|
||||
private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
|
||||
// 获取请求体
|
||||
Flux<DataBuffer> body = serverHttpRequest.getBody();
|
||||
AtomicReference<String> bodyRef = new AtomicReference<>();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.ruoyi.gateway.filter;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
|
|
@ -32,36 +33,30 @@ import reactor.core.publisher.Mono;
|
|||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true")
|
||||
public class XssFilter implements GlobalFilter, Ordered
|
||||
{
|
||||
public class XssFilter implements GlobalFilter, Ordered {
|
||||
// 跨站脚本的 xss 配置,nacos自行添加
|
||||
@Autowired
|
||||
private XssProperties xss;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
|
||||
{
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
// xss开关未开启 或 通过nacos关闭,不过滤
|
||||
if (!xss.getEnabled())
|
||||
{
|
||||
if (!xss.getEnabled()) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
// GET DELETE 不过滤
|
||||
HttpMethod method = request.getMethod();
|
||||
if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE)
|
||||
{
|
||||
if (method == HttpMethod.GET || method == HttpMethod.DELETE) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
// 非json类型,不过滤
|
||||
if (!isJsonRequest(exchange))
|
||||
{
|
||||
if (!isJsonRequest(exchange)) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
// excludeUrls 不过滤
|
||||
String url = request.getURI().getPath();
|
||||
if (StringUtils.matches(url, xss.getExcludeUrls()))
|
||||
{
|
||||
if (StringUtils.matches(url, xss.getExcludeUrls())) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange);
|
||||
|
|
@ -69,13 +64,10 @@ public class XssFilter implements GlobalFilter, Ordered
|
|||
|
||||
}
|
||||
|
||||
private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange)
|
||||
{
|
||||
ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest())
|
||||
{
|
||||
private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) {
|
||||
ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||
@Override
|
||||
public Flux<DataBuffer> getBody()
|
||||
{
|
||||
public Flux<DataBuffer> getBody() {
|
||||
Flux<DataBuffer> body = super.getBody();
|
||||
return body.buffer().map(dataBuffers -> {
|
||||
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
|
||||
|
|
@ -96,8 +88,7 @@ public class XssFilter implements GlobalFilter, Ordered
|
|||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders getHeaders()
|
||||
{
|
||||
public HttpHeaders getHeaders() {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.putAll(super.getHeaders());
|
||||
// 由于修改了请求体的body,导致content-length长度不确定,因此需要删除原先的content-length
|
||||
|
|
@ -112,18 +103,16 @@ public class XssFilter implements GlobalFilter, Ordered
|
|||
|
||||
/**
|
||||
* 是否是Json请求
|
||||
*
|
||||
*
|
||||
* @param exchange HTTP请求
|
||||
*/
|
||||
public boolean isJsonRequest(ServerWebExchange exchange)
|
||||
{
|
||||
public boolean isJsonRequest(ServerWebExchange exchange) {
|
||||
String header = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
|
||||
return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder()
|
||||
{
|
||||
public int getOrder() {
|
||||
return -100;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,33 +19,24 @@ import reactor.core.publisher.Mono;
|
|||
*/
|
||||
@Order(-1)
|
||||
@Configuration
|
||||
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
|
||||
{
|
||||
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);
|
||||
|
||||
@Override
|
||||
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
|
||||
{
|
||||
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
|
||||
ServerHttpResponse response = exchange.getResponse();
|
||||
|
||||
if (exchange.getResponse().isCommitted())
|
||||
{
|
||||
if (exchange.getResponse().isCommitted()) {
|
||||
return Mono.error(ex);
|
||||
}
|
||||
|
||||
String msg;
|
||||
|
||||
if (ex instanceof NotFoundException)
|
||||
{
|
||||
if (ex instanceof NotFoundException) {
|
||||
msg = "服务未找到";
|
||||
}
|
||||
else if (ex instanceof ResponseStatusException)
|
||||
{
|
||||
ResponseStatusException responseStatusException = (ResponseStatusException) ex;
|
||||
} else if (ex instanceof ResponseStatusException responseStatusException) {
|
||||
msg = responseStatusException.getMessage();
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
msg = "内部服务器错误";
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,29 +13,23 @@ import reactor.core.publisher.Mono;
|
|||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SentinelFallbackHandler implements WebExceptionHandler
|
||||
{
|
||||
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange)
|
||||
{
|
||||
public class SentinelFallbackHandler implements WebExceptionHandler {
|
||||
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
|
||||
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求超过最大数,请稍候再试");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
|
||||
{
|
||||
if (exchange.getResponse().isCommitted())
|
||||
{
|
||||
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
|
||||
if (exchange.getResponse().isCommitted()) {
|
||||
return Mono.error(ex);
|
||||
}
|
||||
if (!BlockException.isBlockException(ex))
|
||||
{
|
||||
if (!BlockException.isBlockException(ex)) {
|
||||
return Mono.error(ex);
|
||||
}
|
||||
return handleBlockedRequest(exchange, ex).flatMap(response -> writeResponse(response, exchange));
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable)
|
||||
{
|
||||
private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
|
||||
return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,49 +8,49 @@ import org.springframework.web.bind.annotation.GetMapping;
|
|||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import reactor.core.publisher.Mono;
|
||||
import springfox.documentation.swagger.web.SecurityConfiguration;
|
||||
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
|
||||
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
|
||||
import springfox.documentation.swagger.web.UiConfiguration;
|
||||
import springfox.documentation.swagger.web.UiConfigurationBuilder;
|
||||
//import springfox.documentation.swagger.web.SecurityConfiguration;
|
||||
//import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
|
||||
//import springfox.documentation.swagger.web.SwaggerResourcesProvider;
|
||||
//import springfox.documentation.swagger.web.UiConfiguration;
|
||||
//import springfox.documentation.swagger.web.UiConfigurationBuilder;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/swagger-resources")
|
||||
//@RestController
|
||||
//@RequestMapping("/swagger-resources")
|
||||
public class SwaggerHandler
|
||||
{
|
||||
@Autowired(required = false)
|
||||
private SecurityConfiguration securityConfiguration;
|
||||
|
||||
@Autowired(required = false)
|
||||
private UiConfiguration uiConfiguration;
|
||||
|
||||
private final SwaggerResourcesProvider swaggerResources;
|
||||
|
||||
@Autowired
|
||||
public SwaggerHandler(SwaggerResourcesProvider swaggerResources)
|
||||
{
|
||||
this.swaggerResources = swaggerResources;
|
||||
}
|
||||
|
||||
@GetMapping("/configuration/security")
|
||||
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration()
|
||||
{
|
||||
return Mono.just(new ResponseEntity<>(
|
||||
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()),
|
||||
HttpStatus.OK));
|
||||
}
|
||||
|
||||
@GetMapping("/configuration/ui")
|
||||
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration()
|
||||
{
|
||||
return Mono.just(new ResponseEntity<>(
|
||||
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@GetMapping("")
|
||||
public Mono<ResponseEntity> swaggerResources()
|
||||
{
|
||||
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
|
||||
}
|
||||
// @Autowired(required = false)
|
||||
// private SecurityConfiguration securityConfiguration;
|
||||
//
|
||||
// @Autowired(required = false)
|
||||
// private UiConfiguration uiConfiguration;
|
||||
//
|
||||
// private final SwaggerResourcesProvider swaggerResources;
|
||||
//
|
||||
// @Autowired
|
||||
// public SwaggerHandler(SwaggerResourcesProvider swaggerResources)
|
||||
// {
|
||||
// this.swaggerResources = swaggerResources;
|
||||
// }
|
||||
//
|
||||
// @GetMapping("/configuration/security")
|
||||
// public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration()
|
||||
// {
|
||||
// return Mono.just(new ResponseEntity<>(
|
||||
// Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()),
|
||||
// HttpStatus.OK));
|
||||
// }
|
||||
//
|
||||
// @GetMapping("/configuration/ui")
|
||||
// public Mono<ResponseEntity<UiConfiguration>> uiConfiguration()
|
||||
// {
|
||||
// return Mono.just(new ResponseEntity<>(
|
||||
// Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
|
||||
// }
|
||||
//
|
||||
// @SuppressWarnings("rawtypes")
|
||||
// @GetMapping("")
|
||||
// public Mono<ResponseEntity> swaggerResources()
|
||||
// {
|
||||
// return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.ruoyi.gateway.handler;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
|
@ -19,21 +20,16 @@ import reactor.core.publisher.Mono;
|
|||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class ValidateCodeHandler implements HandlerFunction<ServerResponse>
|
||||
{
|
||||
public class ValidateCodeHandler implements HandlerFunction<ServerResponse> {
|
||||
@Autowired
|
||||
private ValidateCodeService validateCodeService;
|
||||
|
||||
@Override
|
||||
public Mono<ServerResponse> handle(ServerRequest serverRequest)
|
||||
{
|
||||
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
|
||||
AjaxResult ajax;
|
||||
try
|
||||
{
|
||||
try {
|
||||
ajax = validateCodeService.createCaptcha();
|
||||
}
|
||||
catch (CaptchaException | IOException e)
|
||||
{
|
||||
} catch (CaptchaException | IOException e) {
|
||||
return Mono.error(e);
|
||||
}
|
||||
return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.ruoyi.gateway.service;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.ruoyi.common.core.exception.CaptchaException;
|
||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
||||
|
||||
|
|
@ -9,15 +10,14 @@ import com.ruoyi.common.core.web.domain.AjaxResult;
|
|||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public interface ValidateCodeService
|
||||
{
|
||||
public interface ValidateCodeService {
|
||||
/**
|
||||
* 生成验证码
|
||||
*/
|
||||
public AjaxResult createCaptcha() throws IOException, CaptchaException;
|
||||
AjaxResult createCaptcha() throws IOException, CaptchaException;
|
||||
|
||||
/**
|
||||
* 校验验证码
|
||||
*/
|
||||
public void checkCaptcha(String key, String value) throws CaptchaException;
|
||||
void checkCaptcha(String key, String value) throws CaptchaException;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,11 @@ package com.ruoyi.gateway.service.impl;
|
|||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.FastByteArrayOutputStream;
|
||||
|
|
@ -26,8 +29,7 @@ import com.ruoyi.gateway.service.ValidateCodeService;
|
|||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class ValidateCodeServiceImpl implements ValidateCodeService
|
||||
{
|
||||
public class ValidateCodeServiceImpl implements ValidateCodeService {
|
||||
@Resource(name = "captchaProducer")
|
||||
private Producer captchaProducer;
|
||||
|
||||
|
|
@ -44,13 +46,11 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
|
|||
* 生成验证码
|
||||
*/
|
||||
@Override
|
||||
public AjaxResult createCaptcha() throws IOException, CaptchaException
|
||||
{
|
||||
public AjaxResult createCaptcha() throws CaptchaException {
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
boolean captchaEnabled = captchaProperties.getEnabled();
|
||||
ajax.put("captchaEnabled", captchaEnabled);
|
||||
if (!captchaEnabled)
|
||||
{
|
||||
if (!captchaEnabled) {
|
||||
return ajax;
|
||||
}
|
||||
|
||||
|
|
@ -63,15 +63,12 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
|
|||
|
||||
String captchaType = captchaProperties.getType();
|
||||
// 生成验证码
|
||||
if ("math".equals(captchaType))
|
||||
{
|
||||
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))
|
||||
{
|
||||
} else if ("char".equals(captchaType)) {
|
||||
capStr = code = captchaProducer.createText();
|
||||
image = captchaProducer.createImage(capStr);
|
||||
}
|
||||
|
|
@ -79,12 +76,9 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
|
|||
redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
|
||||
// 转换流信息写出
|
||||
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
|
||||
try
|
||||
{
|
||||
try {
|
||||
ImageIO.write(image, "jpg", os);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
} catch (IOException e) {
|
||||
return AjaxResult.error(e.getMessage());
|
||||
}
|
||||
|
||||
|
|
@ -97,22 +91,18 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
|
|||
* 校验验证码
|
||||
*/
|
||||
@Override
|
||||
public void checkCaptcha(String code, String uuid) throws CaptchaException
|
||||
{
|
||||
if (StringUtils.isEmpty(code))
|
||||
{
|
||||
public void checkCaptcha(String code, String uuid) throws CaptchaException {
|
||||
if (StringUtils.isEmpty(code)) {
|
||||
throw new CaptchaException("验证码不能为空");
|
||||
}
|
||||
if (StringUtils.isEmpty(uuid))
|
||||
{
|
||||
if (StringUtils.isEmpty(uuid)) {
|
||||
throw new CaptchaException("验证码已失效");
|
||||
}
|
||||
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
|
||||
String captcha = redisService.getCacheObject(verifyKey);
|
||||
redisService.deleteObject(verifyKey);
|
||||
|
||||
if (!code.equalsIgnoreCase(captcha))
|
||||
{
|
||||
if (!code.equalsIgnoreCase(captcha)) {
|
||||
throw new CaptchaException("验证码错误");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,12 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
|
|
|
|||
|
|
@ -17,15 +17,6 @@ public class RuoYiFileApplication
|
|||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(RuoYiFileApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 文件服务模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 文件服务模块启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
package com.ruoyi.file.config;
|
||||
|
||||
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
|
||||
import com.github.tobato.fastdfs.service.FastFileStorageClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author Alan Scipio
|
||||
* created on 2024/1/31
|
||||
*/
|
||||
//@Configuration
|
||||
public class FastDfsConfig {
|
||||
|
||||
//TODO 未完全对接,待完善
|
||||
// @Bean
|
||||
public FastFileStorageClient fastFileStorageClient() {
|
||||
return new DefaultFastFileStorageClient();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -12,8 +12,7 @@ import io.minio.MinioClient;
|
|||
*/
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "minio")
|
||||
public class MinioConfig
|
||||
{
|
||||
public class MinioConfig {
|
||||
/**
|
||||
* 服务地址
|
||||
*/
|
||||
|
|
@ -34,49 +33,40 @@ public class MinioConfig
|
|||
*/
|
||||
private String bucketName;
|
||||
|
||||
public String getUrl()
|
||||
{
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url)
|
||||
{
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getAccessKey()
|
||||
{
|
||||
public String getAccessKey() {
|
||||
return accessKey;
|
||||
}
|
||||
|
||||
public void setAccessKey(String accessKey)
|
||||
{
|
||||
public void setAccessKey(String accessKey) {
|
||||
this.accessKey = accessKey;
|
||||
}
|
||||
|
||||
public String getSecretKey()
|
||||
{
|
||||
public String getSecretKey() {
|
||||
return secretKey;
|
||||
}
|
||||
|
||||
public void setSecretKey(String secretKey)
|
||||
{
|
||||
public void setSecretKey(String secretKey) {
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public String getBucketName()
|
||||
{
|
||||
public String getBucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
public void setBucketName(String bucketName)
|
||||
{
|
||||
public void setBucketName(String bucketName) {
|
||||
this.bucketName = bucketName;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MinioClient getMinioClient()
|
||||
{
|
||||
public MinioClient getMinioClient() {
|
||||
return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.ruoyi.file.config;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
|
|
@ -9,12 +10,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|||
|
||||
/**
|
||||
* 通用映射配置
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
public class ResourcesConfig implements WebMvcConfigurer
|
||||
{
|
||||
public class ResourcesConfig implements WebMvcConfigurer {
|
||||
/**
|
||||
* 上传文件存储在本地的根路径
|
||||
*/
|
||||
|
|
@ -28,20 +28,19 @@ public class ResourcesConfig implements WebMvcConfigurer
|
|||
public String localFilePrefix;
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry)
|
||||
{
|
||||
/** 本地文件上传路径 */
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
/* 本地文件上传路径 */
|
||||
registry.addResourceHandler(localFilePrefix + "/**")
|
||||
.addResourceLocations("file:" + localFilePath + File.separator);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 开启跨域
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
// 设置允许跨域的路由
|
||||
registry.addMapping(localFilePrefix + "/**")
|
||||
registry.addMapping(localFilePrefix + "/**")
|
||||
// 设置允许跨域请求的域名
|
||||
.allowedOrigins("*")
|
||||
// 设置允许的方法
|
||||
|
|
|
|||
|
|
@ -13,12 +13,11 @@ import com.ruoyi.system.api.domain.SysFile;
|
|||
|
||||
/**
|
||||
* 文件请求处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
public class SysFileController
|
||||
{
|
||||
public class SysFileController {
|
||||
private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
|
||||
|
||||
@Autowired
|
||||
|
|
@ -28,19 +27,15 @@ public class SysFileController
|
|||
* 文件上传请求
|
||||
*/
|
||||
@PostMapping("upload")
|
||||
public R<SysFile> upload(MultipartFile file)
|
||||
{
|
||||
try
|
||||
{
|
||||
public R<SysFile> upload(MultipartFile file) {
|
||||
try {
|
||||
// 上传并返回访问地址
|
||||
String url = sysFileService.uploadFile(file);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(url));
|
||||
sysFile.setUrl(url);
|
||||
return R.ok(sysFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.ruoyi.file.service;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import com.alibaba.nacos.common.utils.IoUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
|
@ -16,15 +17,14 @@ import com.ruoyi.common.core.utils.file.FileTypeUtils;
|
|||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class FastDfsSysFileServiceImpl implements ISysFileService
|
||||
{
|
||||
public class FastDfsSysFileServiceImpl implements ISysFileService {
|
||||
/**
|
||||
* 域名或本机访问地址
|
||||
*/
|
||||
@Value("${fdfs.domain}")
|
||||
public String domain;
|
||||
|
||||
@Autowired
|
||||
// @Autowired
|
||||
private FastFileStorageClient storageClient;
|
||||
|
||||
/**
|
||||
|
|
@ -32,15 +32,15 @@ public class FastDfsSysFileServiceImpl implements ISysFileService
|
|||
*
|
||||
* @param file 上传的文件
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public String uploadFile(MultipartFile file) throws Exception
|
||||
{
|
||||
InputStream inputStream = file.getInputStream();
|
||||
StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
|
||||
FileTypeUtils.getExtension(file), null);
|
||||
IoUtils.closeQuietly(inputStream);
|
||||
return domain + "/" + storePath.getFullPath();
|
||||
public String uploadFile(MultipartFile file) throws Exception {
|
||||
// InputStream inputStream = file.getInputStream();
|
||||
// StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
|
||||
// FileTypeUtils.getExtension(file), null);
|
||||
// IoUtils.closeQuietly(inputStream);
|
||||
// return domain + "/" + storePath.getFullPath();
|
||||
|
||||
return "notImplementedYet";
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import java.io.File;
|
|||
import java.io.IOException;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.ruoyi.common.core.exception.file.FileException;
|
||||
|
|
@ -18,11 +19,10 @@ import com.ruoyi.common.core.utils.uuid.Seq;
|
|||
|
||||
/**
|
||||
* 文件上传工具类
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class FileUploadUtils
|
||||
{
|
||||
public class FileUploadUtils {
|
||||
/**
|
||||
* 默认大小 50M
|
||||
*/
|
||||
|
|
@ -37,22 +37,15 @@ public class FileUploadUtils
|
|||
* 根据文件路径上传
|
||||
*
|
||||
* @param baseDir 相对应用的基目录
|
||||
* @param file 上传的文件
|
||||
* @param file 上传的文件
|
||||
* @return 文件名称
|
||||
* @throws IOException
|
||||
*/
|
||||
public static final String upload(String baseDir, MultipartFile file) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
public static String upload(String baseDir, MultipartFile file) throws IOException {
|
||||
try {
|
||||
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
|
||||
}
|
||||
catch (FileException fe)
|
||||
{
|
||||
} catch (FileException fe) {
|
||||
throw new IOException(fe.getDefaultMessage(), fe);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
|
@ -60,22 +53,20 @@ public class FileUploadUtils
|
|||
/**
|
||||
* 文件上传
|
||||
*
|
||||
* @param baseDir 相对应用的基目录
|
||||
* @param file 上传的文件
|
||||
* @param baseDir 相对应用的基目录
|
||||
* @param file 上传的文件
|
||||
* @param allowedExtension 上传文件类型
|
||||
* @return 返回上传成功的文件名
|
||||
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||
* @throws FileNameLengthLimitExceededException 文件名太长
|
||||
* @throws IOException 比如读写文件出错时
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
* @throws IOException 比如读写文件出错时
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
*/
|
||||
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
|
||||
public static String upload(String baseDir, MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
|
||||
InvalidExtensionException
|
||||
{
|
||||
InvalidExtensionException {
|
||||
int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
|
||||
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
|
||||
{
|
||||
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
|
||||
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
|
||||
}
|
||||
|
||||
|
|
@ -91,28 +82,24 @@ public class FileUploadUtils
|
|||
/**
|
||||
* 编码文件名
|
||||
*/
|
||||
public static final String extractFilename(MultipartFile file)
|
||||
{
|
||||
public static String extractFilename(MultipartFile file) {
|
||||
return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
|
||||
FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), FileTypeUtils.getExtension(file));
|
||||
}
|
||||
|
||||
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
|
||||
{
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
private static File getAbsoluteFile(String uploadDir, String fileName) {
|
||||
File desc = new File(uploadDir + File.separator + fileName);
|
||||
|
||||
if (!desc.exists())
|
||||
{
|
||||
if (!desc.getParentFile().exists())
|
||||
{
|
||||
if (!desc.exists()) {
|
||||
if (!desc.getParentFile().exists()) {
|
||||
desc.getParentFile().mkdirs();
|
||||
}
|
||||
}
|
||||
return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
|
||||
}
|
||||
|
||||
private static final String getPathFileName(String fileName) throws IOException
|
||||
{
|
||||
private static String getPathFileName(String fileName) {
|
||||
String pathFileName = "/" + fileName;
|
||||
return pathFileName;
|
||||
}
|
||||
|
|
@ -122,43 +109,31 @@ public class FileUploadUtils
|
|||
*
|
||||
* @param file 上传的文件
|
||||
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
*/
|
||||
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, InvalidExtensionException
|
||||
{
|
||||
public static void assertAllowed(MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, InvalidExtensionException {
|
||||
long size = file.getSize();
|
||||
if (size > DEFAULT_MAX_SIZE)
|
||||
{
|
||||
if (size > DEFAULT_MAX_SIZE) {
|
||||
throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
|
||||
}
|
||||
|
||||
String fileName = file.getOriginalFilename();
|
||||
String extension = FileTypeUtils.getExtension(file);
|
||||
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
|
||||
{
|
||||
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
|
||||
{
|
||||
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
|
||||
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
|
||||
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
|
||||
{
|
||||
} else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
|
||||
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
|
||||
{
|
||||
} else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
|
||||
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
|
||||
{
|
||||
} else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
|
||||
throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
throw new InvalidExtensionException(allowedExtension, extension, fileName);
|
||||
}
|
||||
}
|
||||
|
|
@ -167,16 +142,13 @@ public class FileUploadUtils
|
|||
/**
|
||||
* 判断MIME类型是否是允许的MIME类型
|
||||
*
|
||||
* @param extension 上传文件类型
|
||||
* @param extension 上传文件类型
|
||||
* @param allowedExtension 允许上传文件类型
|
||||
* @return true/false
|
||||
*/
|
||||
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
|
||||
{
|
||||
for (String str : allowedExtension)
|
||||
{
|
||||
if (str.equalsIgnoreCase(extension))
|
||||
{
|
||||
public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
|
||||
for (String str : allowedExtension) {
|
||||
if (str.equalsIgnoreCase(extension)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,12 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
|
|
@ -42,10 +48,14 @@
|
|||
</dependency>
|
||||
|
||||
<!-- Swagger UI -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Apache Velocity -->
|
||||
|
|
|
|||
|
|
@ -20,15 +20,6 @@ public class RuoYiGenApplication
|
|||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(RuoYiGenApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 代码生成模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 代码生成模块启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import java.io.IOException;
|
|||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
|
@ -30,13 +31,12 @@ import com.ruoyi.gen.service.IGenTableService;
|
|||
|
||||
/**
|
||||
* 代码生成 操作处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RequestMapping("/gen")
|
||||
@RestController
|
||||
public class GenController extends BaseController
|
||||
{
|
||||
public class GenController extends BaseController {
|
||||
@Autowired
|
||||
private IGenTableService genTableService;
|
||||
|
||||
|
|
@ -48,8 +48,7 @@ public class GenController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("tool:gen:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo genList(GenTable genTable)
|
||||
{
|
||||
public TableDataInfo genList(GenTable genTable) {
|
||||
startPage();
|
||||
List<GenTable> list = genTableService.selectGenTableList(genTable);
|
||||
return getDataTable(list);
|
||||
|
|
@ -60,12 +59,11 @@ public class GenController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("tool:gen:query")
|
||||
@GetMapping(value = "/{tableId}")
|
||||
public AjaxResult getInfo(@PathVariable Long tableId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long tableId) {
|
||||
GenTable table = genTableService.selectGenTableById(tableId);
|
||||
List<GenTable> tables = genTableService.selectGenTableAll();
|
||||
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("info", table);
|
||||
map.put("rows", list);
|
||||
map.put("tables", tables);
|
||||
|
|
@ -77,8 +75,7 @@ public class GenController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("tool:gen:list")
|
||||
@GetMapping("/db/list")
|
||||
public TableDataInfo dataList(GenTable genTable)
|
||||
{
|
||||
public TableDataInfo dataList(GenTable genTable) {
|
||||
startPage();
|
||||
List<GenTable> list = genTableService.selectDbTableList(genTable);
|
||||
return getDataTable(list);
|
||||
|
|
@ -88,8 +85,7 @@ public class GenController extends BaseController
|
|||
* 查询数据表字段列表
|
||||
*/
|
||||
@GetMapping(value = "/column/{tableId}")
|
||||
public TableDataInfo columnList(Long tableId)
|
||||
{
|
||||
public TableDataInfo columnList(Long tableId) {
|
||||
TableDataInfo dataInfo = new TableDataInfo();
|
||||
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
|
||||
dataInfo.setRows(list);
|
||||
|
|
@ -103,8 +99,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:import")
|
||||
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
|
||||
@PostMapping("/importTable")
|
||||
public AjaxResult importTableSave(String tables)
|
||||
{
|
||||
public AjaxResult importTableSave(String tables) {
|
||||
String[] tableNames = Convert.toStrArray(tables);
|
||||
// 查询表信息
|
||||
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
|
||||
|
|
@ -118,8 +113,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:edit")
|
||||
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult editSave(@Validated @RequestBody GenTable genTable)
|
||||
{
|
||||
public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {
|
||||
genTableService.validateEdit(genTable);
|
||||
genTableService.updateGenTable(genTable);
|
||||
return success();
|
||||
|
|
@ -131,8 +125,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:remove")
|
||||
@Log(title = "代码生成", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{tableIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] tableIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] tableIds) {
|
||||
genTableService.deleteGenTableByIds(tableIds);
|
||||
return success();
|
||||
}
|
||||
|
|
@ -142,8 +135,7 @@ public class GenController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("tool:gen:preview")
|
||||
@GetMapping("/preview/{tableId}")
|
||||
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
|
||||
{
|
||||
public AjaxResult preview(@PathVariable("tableId") Long tableId) {
|
||||
Map<String, String> dataMap = genTableService.previewCode(tableId);
|
||||
return success(dataMap);
|
||||
}
|
||||
|
|
@ -154,8 +146,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/download/{tableName}")
|
||||
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
|
||||
{
|
||||
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
|
||||
byte[] data = genTableService.downloadCode(tableName);
|
||||
genCode(response, data);
|
||||
}
|
||||
|
|
@ -166,8 +157,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/genCode/{tableName}")
|
||||
public AjaxResult genCode(@PathVariable("tableName") String tableName)
|
||||
{
|
||||
public AjaxResult genCode(@PathVariable("tableName") String tableName) {
|
||||
genTableService.generatorCode(tableName);
|
||||
return success();
|
||||
}
|
||||
|
|
@ -178,8 +168,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:edit")
|
||||
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||
@GetMapping("/synchDb/{tableName}")
|
||||
public AjaxResult synchDb(@PathVariable("tableName") String tableName)
|
||||
{
|
||||
public AjaxResult synchDb(@PathVariable("tableName") String tableName) {
|
||||
genTableService.synchDb(tableName);
|
||||
return success();
|
||||
}
|
||||
|
|
@ -190,8 +179,7 @@ public class GenController extends BaseController
|
|||
@RequiresPermissions("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/batchGenCode")
|
||||
public void batchGenCode(HttpServletResponse response, String tables) throws IOException
|
||||
{
|
||||
public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
|
||||
String[] tableNames = Convert.toStrArray(tables);
|
||||
byte[] data = genTableService.downloadCode(tableNames);
|
||||
genCode(response, data);
|
||||
|
|
@ -200,8 +188,7 @@ public class GenController extends BaseController
|
|||
/**
|
||||
* 生成zip文件
|
||||
*/
|
||||
private void genCode(HttpServletResponse response, byte[] data) throws IOException
|
||||
{
|
||||
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
|
||||
response.reset();
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
|
||||
response.addHeader("Content-Length", "" + data.length);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
package com.ruoyi.gen.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import com.ruoyi.common.core.constant.GenConstants;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
|
|
@ -15,6 +16,7 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
|
|||
*/
|
||||
public class GenTable extends BaseEntity
|
||||
{
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 编号 */
|
||||
|
|
|
|||
|
|
@ -1,336 +1,321 @@
|
|||
package com.ruoyi.gen.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 代码生成业务字段表 gen_table_column
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class GenTableColumn extends BaseEntity
|
||||
{
|
||||
public class GenTableColumn extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 编号 */
|
||||
/**
|
||||
* 编号
|
||||
*/
|
||||
private Long columnId;
|
||||
|
||||
/** 归属表编号 */
|
||||
/**
|
||||
* 归属表编号
|
||||
*/
|
||||
private Long tableId;
|
||||
|
||||
/** 列名称 */
|
||||
/**
|
||||
* 列名称
|
||||
*/
|
||||
private String columnName;
|
||||
|
||||
/** 列描述 */
|
||||
/**
|
||||
* 列描述
|
||||
*/
|
||||
private String columnComment;
|
||||
|
||||
/** 列类型 */
|
||||
/**
|
||||
* 列类型
|
||||
*/
|
||||
private String columnType;
|
||||
|
||||
/** JAVA类型 */
|
||||
/**
|
||||
* JAVA类型
|
||||
*/
|
||||
private String javaType;
|
||||
|
||||
/** JAVA字段名 */
|
||||
/**
|
||||
* JAVA字段名
|
||||
*/
|
||||
@NotBlank(message = "Java属性不能为空")
|
||||
private String javaField;
|
||||
|
||||
/** 是否主键(1是) */
|
||||
/**
|
||||
* 是否主键(1是)
|
||||
*/
|
||||
private String isPk;
|
||||
|
||||
/** 是否自增(1是) */
|
||||
/**
|
||||
* 是否自增(1是)
|
||||
*/
|
||||
private String isIncrement;
|
||||
|
||||
/** 是否必填(1是) */
|
||||
/**
|
||||
* 是否必填(1是)
|
||||
*/
|
||||
private String isRequired;
|
||||
|
||||
/** 是否为插入字段(1是) */
|
||||
/**
|
||||
* 是否为插入字段(1是)
|
||||
*/
|
||||
private String isInsert;
|
||||
|
||||
/** 是否编辑字段(1是) */
|
||||
/**
|
||||
* 是否编辑字段(1是)
|
||||
*/
|
||||
private String isEdit;
|
||||
|
||||
/** 是否列表字段(1是) */
|
||||
/**
|
||||
* 是否列表字段(1是)
|
||||
*/
|
||||
private String isList;
|
||||
|
||||
/** 是否查询字段(1是) */
|
||||
/**
|
||||
* 是否查询字段(1是)
|
||||
*/
|
||||
private String isQuery;
|
||||
|
||||
/** 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) */
|
||||
/**
|
||||
* 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围)
|
||||
*/
|
||||
private String queryType;
|
||||
|
||||
/** 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件) */
|
||||
/**
|
||||
* 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件)
|
||||
*/
|
||||
private String htmlType;
|
||||
|
||||
/** 字典类型 */
|
||||
/**
|
||||
* 字典类型
|
||||
*/
|
||||
private String dictType;
|
||||
|
||||
/** 排序 */
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
private Integer sort;
|
||||
|
||||
public void setColumnId(Long columnId)
|
||||
{
|
||||
public void setColumnId(Long columnId) {
|
||||
this.columnId = columnId;
|
||||
}
|
||||
|
||||
public Long getColumnId()
|
||||
{
|
||||
public Long getColumnId() {
|
||||
return columnId;
|
||||
}
|
||||
|
||||
public void setTableId(Long tableId)
|
||||
{
|
||||
public void setTableId(Long tableId) {
|
||||
this.tableId = tableId;
|
||||
}
|
||||
|
||||
public Long getTableId()
|
||||
{
|
||||
public Long getTableId() {
|
||||
return tableId;
|
||||
}
|
||||
|
||||
public void setColumnName(String columnName)
|
||||
{
|
||||
public void setColumnName(String columnName) {
|
||||
this.columnName = columnName;
|
||||
}
|
||||
|
||||
public String getColumnName()
|
||||
{
|
||||
public String getColumnName() {
|
||||
return columnName;
|
||||
}
|
||||
|
||||
public void setColumnComment(String columnComment)
|
||||
{
|
||||
public void setColumnComment(String columnComment) {
|
||||
this.columnComment = columnComment;
|
||||
}
|
||||
|
||||
public String getColumnComment()
|
||||
{
|
||||
public String getColumnComment() {
|
||||
return columnComment;
|
||||
}
|
||||
|
||||
public void setColumnType(String columnType)
|
||||
{
|
||||
public void setColumnType(String columnType) {
|
||||
this.columnType = columnType;
|
||||
}
|
||||
|
||||
public String getColumnType()
|
||||
{
|
||||
public String getColumnType() {
|
||||
return columnType;
|
||||
}
|
||||
|
||||
public void setJavaType(String javaType)
|
||||
{
|
||||
public void setJavaType(String javaType) {
|
||||
this.javaType = javaType;
|
||||
}
|
||||
|
||||
public String getJavaType()
|
||||
{
|
||||
public String getJavaType() {
|
||||
return javaType;
|
||||
}
|
||||
|
||||
public void setJavaField(String javaField)
|
||||
{
|
||||
public void setJavaField(String javaField) {
|
||||
this.javaField = javaField;
|
||||
}
|
||||
|
||||
public String getJavaField()
|
||||
{
|
||||
public String getJavaField() {
|
||||
return javaField;
|
||||
}
|
||||
|
||||
public String getCapJavaField()
|
||||
{
|
||||
public String getCapJavaField() {
|
||||
return StringUtils.capitalize(javaField);
|
||||
}
|
||||
|
||||
public void setIsPk(String isPk)
|
||||
{
|
||||
public void setIsPk(String isPk) {
|
||||
this.isPk = isPk;
|
||||
}
|
||||
|
||||
public String getIsPk()
|
||||
{
|
||||
public String getIsPk() {
|
||||
return isPk;
|
||||
}
|
||||
|
||||
public boolean isPk()
|
||||
{
|
||||
public boolean isPk() {
|
||||
return isPk(this.isPk);
|
||||
}
|
||||
|
||||
public boolean isPk(String isPk)
|
||||
{
|
||||
public boolean isPk(String isPk) {
|
||||
return isPk != null && StringUtils.equals("1", isPk);
|
||||
}
|
||||
|
||||
public String getIsIncrement()
|
||||
{
|
||||
public String getIsIncrement() {
|
||||
return isIncrement;
|
||||
}
|
||||
|
||||
public void setIsIncrement(String isIncrement)
|
||||
{
|
||||
public void setIsIncrement(String isIncrement) {
|
||||
this.isIncrement = isIncrement;
|
||||
}
|
||||
|
||||
public boolean isIncrement()
|
||||
{
|
||||
public boolean isIncrement() {
|
||||
return isIncrement(this.isIncrement);
|
||||
}
|
||||
|
||||
public boolean isIncrement(String isIncrement)
|
||||
{
|
||||
public boolean isIncrement(String isIncrement) {
|
||||
return isIncrement != null && StringUtils.equals("1", isIncrement);
|
||||
}
|
||||
|
||||
public void setIsRequired(String isRequired)
|
||||
{
|
||||
public void setIsRequired(String isRequired) {
|
||||
this.isRequired = isRequired;
|
||||
}
|
||||
|
||||
public String getIsRequired()
|
||||
{
|
||||
public String getIsRequired() {
|
||||
return isRequired;
|
||||
}
|
||||
|
||||
public boolean isRequired()
|
||||
{
|
||||
public boolean isRequired() {
|
||||
return isRequired(this.isRequired);
|
||||
}
|
||||
|
||||
public boolean isRequired(String isRequired)
|
||||
{
|
||||
public boolean isRequired(String isRequired) {
|
||||
return isRequired != null && StringUtils.equals("1", isRequired);
|
||||
}
|
||||
|
||||
public void setIsInsert(String isInsert)
|
||||
{
|
||||
public void setIsInsert(String isInsert) {
|
||||
this.isInsert = isInsert;
|
||||
}
|
||||
|
||||
public String getIsInsert()
|
||||
{
|
||||
public String getIsInsert() {
|
||||
return isInsert;
|
||||
}
|
||||
|
||||
public boolean isInsert()
|
||||
{
|
||||
public boolean isInsert() {
|
||||
return isInsert(this.isInsert);
|
||||
}
|
||||
|
||||
public boolean isInsert(String isInsert)
|
||||
{
|
||||
public boolean isInsert(String isInsert) {
|
||||
return isInsert != null && StringUtils.equals("1", isInsert);
|
||||
}
|
||||
|
||||
public void setIsEdit(String isEdit)
|
||||
{
|
||||
public void setIsEdit(String isEdit) {
|
||||
this.isEdit = isEdit;
|
||||
}
|
||||
|
||||
public String getIsEdit()
|
||||
{
|
||||
public String getIsEdit() {
|
||||
return isEdit;
|
||||
}
|
||||
|
||||
public boolean isEdit()
|
||||
{
|
||||
public boolean isEdit() {
|
||||
return isInsert(this.isEdit);
|
||||
}
|
||||
|
||||
public boolean isEdit(String isEdit)
|
||||
{
|
||||
public boolean isEdit(String isEdit) {
|
||||
return isEdit != null && StringUtils.equals("1", isEdit);
|
||||
}
|
||||
|
||||
public void setIsList(String isList)
|
||||
{
|
||||
public void setIsList(String isList) {
|
||||
this.isList = isList;
|
||||
}
|
||||
|
||||
public String getIsList()
|
||||
{
|
||||
public String getIsList() {
|
||||
return isList;
|
||||
}
|
||||
|
||||
public boolean isList()
|
||||
{
|
||||
public boolean isList() {
|
||||
return isList(this.isList);
|
||||
}
|
||||
|
||||
public boolean isList(String isList)
|
||||
{
|
||||
public boolean isList(String isList) {
|
||||
return isList != null && StringUtils.equals("1", isList);
|
||||
}
|
||||
|
||||
public void setIsQuery(String isQuery)
|
||||
{
|
||||
public void setIsQuery(String isQuery) {
|
||||
this.isQuery = isQuery;
|
||||
}
|
||||
|
||||
public String getIsQuery()
|
||||
{
|
||||
public String getIsQuery() {
|
||||
return isQuery;
|
||||
}
|
||||
|
||||
public boolean isQuery()
|
||||
{
|
||||
public boolean isQuery() {
|
||||
return isQuery(this.isQuery);
|
||||
}
|
||||
|
||||
public boolean isQuery(String isQuery)
|
||||
{
|
||||
public boolean isQuery(String isQuery) {
|
||||
return isQuery != null && StringUtils.equals("1", isQuery);
|
||||
}
|
||||
|
||||
public void setQueryType(String queryType)
|
||||
{
|
||||
public void setQueryType(String queryType) {
|
||||
this.queryType = queryType;
|
||||
}
|
||||
|
||||
public String getQueryType()
|
||||
{
|
||||
public String getQueryType() {
|
||||
return queryType;
|
||||
}
|
||||
|
||||
public String getHtmlType()
|
||||
{
|
||||
public String getHtmlType() {
|
||||
return htmlType;
|
||||
}
|
||||
|
||||
public void setHtmlType(String htmlType)
|
||||
{
|
||||
public void setHtmlType(String htmlType) {
|
||||
this.htmlType = htmlType;
|
||||
}
|
||||
|
||||
public void setDictType(String dictType)
|
||||
{
|
||||
public void setDictType(String dictType) {
|
||||
this.dictType = dictType;
|
||||
}
|
||||
|
||||
public String getDictType()
|
||||
{
|
||||
public String getDictType() {
|
||||
return dictType;
|
||||
}
|
||||
|
||||
public void setSort(Integer sort)
|
||||
{
|
||||
public void setSort(Integer sort) {
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
public Integer getSort()
|
||||
{
|
||||
public Integer getSort() {
|
||||
return sort;
|
||||
}
|
||||
|
||||
public boolean isSuperColumn()
|
||||
{
|
||||
public boolean isSuperColumn() {
|
||||
return isSuperColumn(this.javaField);
|
||||
}
|
||||
|
||||
public static boolean isSuperColumn(String javaField)
|
||||
{
|
||||
public static boolean isSuperColumn(String javaField) {
|
||||
return StringUtils.equalsAnyIgnoreCase(javaField,
|
||||
// BaseEntity
|
||||
"createBy", "createTime", "updateBy", "updateTime", "remark",
|
||||
|
|
@ -338,36 +323,28 @@ public class GenTableColumn extends BaseEntity
|
|||
"parentName", "parentId", "orderNum", "ancestors");
|
||||
}
|
||||
|
||||
public boolean isUsableColumn()
|
||||
{
|
||||
public boolean isUsableColumn() {
|
||||
return isUsableColumn(javaField);
|
||||
}
|
||||
|
||||
public static boolean isUsableColumn(String javaField)
|
||||
{
|
||||
public static boolean isUsableColumn(String javaField) {
|
||||
// isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单
|
||||
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
|
||||
}
|
||||
|
||||
public String readConverterExp()
|
||||
{
|
||||
public String readConverterExp() {
|
||||
String remarks = StringUtils.substringBetween(this.columnComment, "(", ")");
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (StringUtils.isNotEmpty(remarks))
|
||||
{
|
||||
for (String value : remarks.split(" "))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(value))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(remarks)) {
|
||||
for (String value : remarks.split(" ")) {
|
||||
if (StringUtils.isNotEmpty(value)) {
|
||||
Object startStr = value.subSequence(0, 1);
|
||||
String endStr = value.substring(1);
|
||||
sb.append("").append(startStr).append("=").append(endStr).append(",");
|
||||
}
|
||||
}
|
||||
return sb.deleteCharAt(sb.length() - 1).toString();
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
return this.columnComment;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,83 +1,83 @@
|
|||
package com.ruoyi.gen.mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ruoyi.gen.domain.GenTable;
|
||||
|
||||
/**
|
||||
* 业务 数据层
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public interface GenTableMapper
|
||||
{
|
||||
public interface GenTableMapper {
|
||||
/**
|
||||
* 查询业务列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 业务集合
|
||||
*/
|
||||
public List<GenTable> selectGenTableList(GenTable genTable);
|
||||
List<GenTable> selectGenTableList(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
public List<GenTable> selectDbTableList(GenTable genTable);
|
||||
List<GenTable> selectDbTableList(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param tableNames 表名称组
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
public List<GenTable> selectDbTableListByNames(String[] tableNames);
|
||||
List<GenTable> selectDbTableListByNames(String[] tableNames);
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
public List<GenTable> selectGenTableAll();
|
||||
List<GenTable> selectGenTableAll();
|
||||
|
||||
/**
|
||||
* 查询表ID业务信息
|
||||
*
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
public GenTable selectGenTableById(Long id);
|
||||
GenTable selectGenTableById(Long id);
|
||||
|
||||
/**
|
||||
* 查询表名称业务信息
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 业务信息
|
||||
*/
|
||||
public GenTable selectGenTableByName(String tableName);
|
||||
GenTable selectGenTableByName(String tableName);
|
||||
|
||||
/**
|
||||
* 新增业务
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 结果
|
||||
*/
|
||||
public int insertGenTable(GenTable genTable);
|
||||
int insertGenTable(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 修改业务
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 结果
|
||||
*/
|
||||
public int updateGenTable(GenTable genTable);
|
||||
int updateGenTable(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 批量删除业务
|
||||
*
|
||||
*
|
||||
* @param ids 需要删除的数据ID
|
||||
* @return 结果
|
||||
*/
|
||||
public int deleteGenTableByIds(Long[] ids);
|
||||
int deleteGenTableByIds(Long[] ids);
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import java.util.function.Function;
|
|||
import java.util.stream.Collectors;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.velocity.Template;
|
||||
|
|
@ -39,12 +40,11 @@ import com.ruoyi.gen.util.VelocityUtils;
|
|||
|
||||
/**
|
||||
* 业务 服务层实现
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class GenTableServiceImpl implements IGenTableService
|
||||
{
|
||||
public class GenTableServiceImpl implements IGenTableService {
|
||||
private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
|
||||
|
||||
@Autowired
|
||||
|
|
@ -55,13 +55,12 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 查询业务信息
|
||||
*
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
@Override
|
||||
public GenTable selectGenTableById(Long id)
|
||||
{
|
||||
public GenTable selectGenTableById(Long id) {
|
||||
GenTable genTable = genTableMapper.selectGenTableById(id);
|
||||
setTableFromOptions(genTable);
|
||||
return genTable;
|
||||
|
|
@ -69,68 +68,60 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 查询业务列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 业务集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTable> selectGenTableList(GenTable genTable)
|
||||
{
|
||||
public List<GenTable> selectGenTableList(GenTable genTable) {
|
||||
return genTableMapper.selectGenTableList(genTable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTable> selectDbTableList(GenTable genTable)
|
||||
{
|
||||
public List<GenTable> selectDbTableList(GenTable genTable) {
|
||||
return genTableMapper.selectDbTableList(genTable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param tableNames 表名称组
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTable> selectDbTableListByNames(String[] tableNames)
|
||||
{
|
||||
public List<GenTable> selectDbTableListByNames(String[] tableNames) {
|
||||
return genTableMapper.selectDbTableListByNames(tableNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTable> selectGenTableAll()
|
||||
{
|
||||
public List<GenTable> selectGenTableAll() {
|
||||
return genTableMapper.selectGenTableAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改业务
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateGenTable(GenTable genTable)
|
||||
{
|
||||
public void updateGenTable(GenTable genTable) {
|
||||
String options = JSON.toJSONString(genTable.getParams());
|
||||
genTable.setOptions(options);
|
||||
int row = genTableMapper.updateGenTable(genTable);
|
||||
if (row > 0)
|
||||
{
|
||||
for (GenTableColumn cenTableColumn : genTable.getColumns())
|
||||
{
|
||||
if (row > 0) {
|
||||
for (GenTableColumn cenTableColumn : genTable.getColumns()) {
|
||||
genTableColumnMapper.updateGenTableColumn(cenTableColumn);
|
||||
}
|
||||
}
|
||||
|
|
@ -138,62 +129,52 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 删除业务对象
|
||||
*
|
||||
*
|
||||
* @param tableIds 需要删除的数据ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteGenTableByIds(Long[] tableIds)
|
||||
{
|
||||
public void deleteGenTableByIds(Long[] tableIds) {
|
||||
genTableMapper.deleteGenTableByIds(tableIds);
|
||||
genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入表结构
|
||||
*
|
||||
*
|
||||
* @param tableList 导入表列表
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void importGenTable(List<GenTable> tableList)
|
||||
{
|
||||
public void importGenTable(List<GenTable> tableList) {
|
||||
String operName = SecurityUtils.getUsername();
|
||||
try
|
||||
{
|
||||
for (GenTable table : tableList)
|
||||
{
|
||||
try {
|
||||
for (GenTable table : tableList) {
|
||||
String tableName = table.getTableName();
|
||||
GenUtils.initTable(table, operName);
|
||||
int row = genTableMapper.insertGenTable(table);
|
||||
if (row > 0)
|
||||
{
|
||||
if (row > 0) {
|
||||
// 保存列信息
|
||||
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
|
||||
for (GenTableColumn column : genTableColumns)
|
||||
{
|
||||
for (GenTableColumn column : genTableColumns) {
|
||||
GenUtils.initColumnField(column, table);
|
||||
genTableColumnMapper.insertGenTableColumn(column);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("导入失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览代码
|
||||
*
|
||||
*
|
||||
* @param tableId 表编号
|
||||
* @return 预览数据列表
|
||||
*/
|
||||
@Override
|
||||
public Map<String, String> previewCode(Long tableId)
|
||||
{
|
||||
public Map<String, String> previewCode(Long tableId) {
|
||||
Map<String, String> dataMap = new LinkedHashMap<>();
|
||||
// 查询表信息
|
||||
GenTable table = genTableMapper.selectGenTableById(tableId);
|
||||
|
|
@ -207,8 +188,7 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
|
||||
for (String template : templates)
|
||||
{
|
||||
for (String template : templates) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
|
|
@ -220,13 +200,12 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 生成代码(下载方式)
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 数据
|
||||
*/
|
||||
@Override
|
||||
public byte[] downloadCode(String tableName)
|
||||
{
|
||||
public byte[] downloadCode(String tableName) {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(outputStream);
|
||||
generatorCode(tableName, zip);
|
||||
|
|
@ -236,12 +215,11 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 生成代码(自定义路径)
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
*/
|
||||
@Override
|
||||
public void generatorCode(String tableName)
|
||||
{
|
||||
public void generatorCode(String tableName) {
|
||||
// 查询表信息
|
||||
GenTable table = genTableMapper.selectGenTableByName(tableName);
|
||||
// 设置主子表信息
|
||||
|
|
@ -255,21 +233,16 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
|
||||
for (String template : templates)
|
||||
{
|
||||
if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
|
||||
{
|
||||
for (String template : templates) {
|
||||
if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
tpl.merge(context, sw);
|
||||
try
|
||||
{
|
||||
try {
|
||||
String path = getGenPath(table, template);
|
||||
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
} catch (IOException e) {
|
||||
throw new ServiceException("渲染模板失败,表名:" + table.getTableName());
|
||||
}
|
||||
}
|
||||
|
|
@ -278,72 +251,62 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 同步数据库
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void synchDb(String tableName)
|
||||
{
|
||||
public void synchDb(String tableName) {
|
||||
GenTable table = genTableMapper.selectGenTableByName(tableName);
|
||||
List<GenTableColumn> tableColumns = table.getColumns();
|
||||
Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));
|
||||
|
||||
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
|
||||
if (StringUtils.isEmpty(dbTableColumns))
|
||||
{
|
||||
if (StringUtils.isEmpty(dbTableColumns)) {
|
||||
throw new ServiceException("同步数据失败,原表结构不存在");
|
||||
}
|
||||
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
|
||||
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).toList();
|
||||
|
||||
dbTableColumns.forEach(column -> {
|
||||
GenUtils.initColumnField(column, table);
|
||||
if (tableColumnMap.containsKey(column.getColumnName()))
|
||||
{
|
||||
if (tableColumnMap.containsKey(column.getColumnName())) {
|
||||
GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
|
||||
column.setColumnId(prevColumn.getColumnId());
|
||||
if (column.isList())
|
||||
{
|
||||
if (column.isList()) {
|
||||
// 如果是列表,继续保留查询方式/字典类型选项
|
||||
column.setDictType(prevColumn.getDictType());
|
||||
column.setQueryType(prevColumn.getQueryType());
|
||||
}
|
||||
if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
|
||||
&& (column.isInsert() || column.isEdit())
|
||||
&& ((column.isUsableColumn()) || (!column.isSuperColumn())))
|
||||
{
|
||||
&& ((column.isUsableColumn()) || (!column.isSuperColumn()))) {
|
||||
// 如果是(新增/修改&非主键/非忽略及父属性),继续保留必填/显示类型选项
|
||||
column.setIsRequired(prevColumn.getIsRequired());
|
||||
column.setHtmlType(prevColumn.getHtmlType());
|
||||
}
|
||||
genTableColumnMapper.updateGenTableColumn(column);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
genTableColumnMapper.insertGenTableColumn(column);
|
||||
}
|
||||
});
|
||||
|
||||
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
|
||||
if (StringUtils.isNotEmpty(delColumns))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(delColumns)) {
|
||||
genTableColumnMapper.deleteGenTableColumns(delColumns);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量生成代码(下载方式)
|
||||
*
|
||||
*
|
||||
* @param tableNames 表数组
|
||||
* @return 数据
|
||||
*/
|
||||
@Override
|
||||
public byte[] downloadCode(String[] tableNames)
|
||||
{
|
||||
public byte[] downloadCode(String[] tableNames) {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(outputStream);
|
||||
for (String tableName : tableNames)
|
||||
{
|
||||
for (String tableName : tableNames) {
|
||||
generatorCode(tableName, zip);
|
||||
}
|
||||
IOUtils.closeQuietly(zip);
|
||||
|
|
@ -353,8 +316,7 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
/**
|
||||
* 查询表信息并生成代码
|
||||
*/
|
||||
private void generatorCode(String tableName, ZipOutputStream zip)
|
||||
{
|
||||
private void generatorCode(String tableName, ZipOutputStream zip) {
|
||||
// 查询表信息
|
||||
GenTable table = genTableMapper.selectGenTableByName(tableName);
|
||||
// 设置主子表信息
|
||||
|
|
@ -368,23 +330,19 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
|
||||
for (String template : templates)
|
||||
{
|
||||
for (String template : templates) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
tpl.merge(context, sw);
|
||||
try
|
||||
{
|
||||
try {
|
||||
// 添加到zip
|
||||
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
|
||||
IOUtils.write(sw.toString(), zip, Constants.UTF8);
|
||||
IOUtils.closeQuietly(sw);
|
||||
zip.flush();
|
||||
zip.closeEntry();
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
} catch (IOException e) {
|
||||
log.error("渲染模板失败,表名:" + table.getTableName(), e);
|
||||
}
|
||||
}
|
||||
|
|
@ -392,36 +350,24 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 修改保存参数校验
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
@Override
|
||||
public void validateEdit(GenTable genTable)
|
||||
{
|
||||
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
|
||||
{
|
||||
public void validateEdit(GenTable genTable) {
|
||||
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
|
||||
String options = JSON.toJSONString(genTable.getParams());
|
||||
JSONObject paramsObj = JSON.parseObject(options);
|
||||
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
|
||||
{
|
||||
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
|
||||
throw new ServiceException("树编码字段不能为空");
|
||||
}
|
||||
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
|
||||
{
|
||||
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
|
||||
throw new ServiceException("树父编码字段不能为空");
|
||||
}
|
||||
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
|
||||
{
|
||||
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
|
||||
throw new ServiceException("树名称字段不能为空");
|
||||
}
|
||||
else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
|
||||
{
|
||||
if (StringUtils.isEmpty(genTable.getSubTableName()))
|
||||
{
|
||||
} else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
|
||||
if (StringUtils.isEmpty(genTable.getSubTableName())) {
|
||||
throw new ServiceException("关联子表的表名不能为空");
|
||||
}
|
||||
else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
|
||||
{
|
||||
} else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
|
||||
throw new ServiceException("子表关联的外键名不能为空");
|
||||
}
|
||||
}
|
||||
|
|
@ -430,64 +376,52 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 设置主键列信息
|
||||
*
|
||||
*
|
||||
* @param table 业务表信息
|
||||
*/
|
||||
public void setPkColumn(GenTable table)
|
||||
{
|
||||
for (GenTableColumn column : table.getColumns())
|
||||
{
|
||||
if (column.isPk())
|
||||
{
|
||||
public void setPkColumn(GenTable table) {
|
||||
for (GenTableColumn column : table.getColumns()) {
|
||||
if (column.isPk()) {
|
||||
table.setPkColumn(column);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNull(table.getPkColumn()))
|
||||
{
|
||||
table.setPkColumn(table.getColumns().get(0));
|
||||
if (StringUtils.isNull(table.getPkColumn())) {
|
||||
table.setPkColumn(table.getColumns().getFirst());
|
||||
}
|
||||
if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
|
||||
{
|
||||
for (GenTableColumn column : table.getSubTable().getColumns())
|
||||
{
|
||||
if (column.isPk())
|
||||
{
|
||||
if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
|
||||
for (GenTableColumn column : table.getSubTable().getColumns()) {
|
||||
if (column.isPk()) {
|
||||
table.getSubTable().setPkColumn(column);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNull(table.getSubTable().getPkColumn()))
|
||||
{
|
||||
table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
|
||||
if (StringUtils.isNull(table.getSubTable().getPkColumn())) {
|
||||
table.getSubTable().setPkColumn(table.getSubTable().getColumns().getFirst());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置主子表信息
|
||||
*
|
||||
*
|
||||
* @param table 业务表信息
|
||||
*/
|
||||
public void setSubTable(GenTable table)
|
||||
{
|
||||
public void setSubTable(GenTable table) {
|
||||
String subTableName = table.getSubTableName();
|
||||
if (StringUtils.isNotEmpty(subTableName))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(subTableName)) {
|
||||
table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代码生成其他选项值
|
||||
*
|
||||
*
|
||||
* @param genTable 设置后的生成对象
|
||||
*/
|
||||
public void setTableFromOptions(GenTable genTable)
|
||||
{
|
||||
public void setTableFromOptions(GenTable genTable) {
|
||||
JSONObject paramsObj = JSON.parseObject(genTable.getOptions());
|
||||
if (StringUtils.isNotNull(paramsObj))
|
||||
{
|
||||
if (StringUtils.isNotNull(paramsObj)) {
|
||||
String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
|
||||
String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
|
||||
String treeName = paramsObj.getString(GenConstants.TREE_NAME);
|
||||
|
|
@ -504,16 +438,14 @@ public class GenTableServiceImpl implements IGenTableService
|
|||
|
||||
/**
|
||||
* 获取代码生成地址
|
||||
*
|
||||
* @param table 业务表信息
|
||||
*
|
||||
* @param table 业务表信息
|
||||
* @param template 模板文件路径
|
||||
* @return 生成地址
|
||||
*/
|
||||
public static String getGenPath(GenTable table, String template)
|
||||
{
|
||||
public static String getGenPath(GenTable table, String template) {
|
||||
String genPath = table.getGenPath();
|
||||
if (StringUtils.equals(genPath, "/"))
|
||||
{
|
||||
if (StringUtils.equals(genPath, "/")) {
|
||||
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
|
||||
}
|
||||
return genPath + File.separator + VelocityUtils.getFileName(template, table);
|
||||
|
|
|
|||
|
|
@ -2,120 +2,117 @@ package com.ruoyi.gen.service;
|
|||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ruoyi.gen.domain.GenTable;
|
||||
|
||||
/**
|
||||
* 业务 服务层
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public interface IGenTableService
|
||||
{
|
||||
public interface IGenTableService {
|
||||
/**
|
||||
* 查询业务列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 业务集合
|
||||
*/
|
||||
public List<GenTable> selectGenTableList(GenTable genTable);
|
||||
List<GenTable> selectGenTableList(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
public List<GenTable> selectDbTableList(GenTable genTable);
|
||||
List<GenTable> selectDbTableList(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
*
|
||||
* @param tableNames 表名称组
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
public List<GenTable> selectDbTableListByNames(String[] tableNames);
|
||||
List<GenTable> selectDbTableListByNames(String[] tableNames);
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
public List<GenTable> selectGenTableAll();
|
||||
List<GenTable> selectGenTableAll();
|
||||
|
||||
/**
|
||||
* 查询业务信息
|
||||
*
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
public GenTable selectGenTableById(Long id);
|
||||
GenTable selectGenTableById(Long id);
|
||||
|
||||
/**
|
||||
* 修改业务
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 结果
|
||||
*/
|
||||
public void updateGenTable(GenTable genTable);
|
||||
void updateGenTable(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 删除业务信息
|
||||
*
|
||||
*
|
||||
* @param tableIds 需要删除的表数据ID
|
||||
* @return 结果
|
||||
*/
|
||||
public void deleteGenTableByIds(Long[] tableIds);
|
||||
void deleteGenTableByIds(Long[] tableIds);
|
||||
|
||||
/**
|
||||
* 导入表结构
|
||||
*
|
||||
*
|
||||
* @param tableList 导入表列表
|
||||
*/
|
||||
public void importGenTable(List<GenTable> tableList);
|
||||
void importGenTable(List<GenTable> tableList);
|
||||
|
||||
/**
|
||||
* 预览代码
|
||||
*
|
||||
*
|
||||
* @param tableId 表编号
|
||||
* @return 预览数据列表
|
||||
*/
|
||||
public Map<String, String> previewCode(Long tableId);
|
||||
Map<String, String> previewCode(Long tableId);
|
||||
|
||||
/**
|
||||
* 生成代码(下载方式)
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 数据
|
||||
*/
|
||||
public byte[] downloadCode(String tableName);
|
||||
byte[] downloadCode(String tableName);
|
||||
|
||||
/**
|
||||
* 生成代码(自定义路径)
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 数据
|
||||
*/
|
||||
public void generatorCode(String tableName);
|
||||
void generatorCode(String tableName);
|
||||
|
||||
/**
|
||||
* 同步数据库
|
||||
*
|
||||
*
|
||||
* @param tableName 表名称
|
||||
*/
|
||||
public void synchDb(String tableName);
|
||||
void synchDb(String tableName);
|
||||
|
||||
/**
|
||||
* 批量生成代码(下载方式)
|
||||
*
|
||||
*
|
||||
* @param tableNames 表数组
|
||||
* @return 数据
|
||||
*/
|
||||
public byte[] downloadCode(String[] tableNames);
|
||||
byte[] downloadCode(String[] tableNames);
|
||||
|
||||
/**
|
||||
* 修改保存参数校验
|
||||
*
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
public void validateEdit(GenTable genTable);
|
||||
void validateEdit(GenTable genTable);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,12 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
|
|
@ -42,12 +48,16 @@
|
|||
</dependency>
|
||||
|
||||
<!-- Swagger UI -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Quartz -->
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
|
|
|
|||
|
|
@ -20,15 +20,6 @@ public class RuoYiJobApplication
|
|||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(RuoYiJobApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 定时任务模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 定时任务模块启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.job.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.quartz.SchedulerException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -30,13 +31,12 @@ import com.ruoyi.job.util.ScheduleUtils;
|
|||
|
||||
/**
|
||||
* 调度任务信息操作处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/job")
|
||||
public class SysJobController extends BaseController
|
||||
{
|
||||
public class SysJobController extends BaseController {
|
||||
@Autowired
|
||||
private ISysJobService jobService;
|
||||
|
||||
|
|
@ -45,8 +45,7 @@ public class SysJobController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("monitor:job:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysJob sysJob)
|
||||
{
|
||||
public TableDataInfo list(SysJob sysJob) {
|
||||
startPage();
|
||||
List<SysJob> list = jobService.selectJobList(sysJob);
|
||||
return getDataTable(list);
|
||||
|
|
@ -58,8 +57,7 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:export")
|
||||
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysJob sysJob)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysJob sysJob) {
|
||||
List<SysJob> list = jobService.selectJobList(sysJob);
|
||||
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
|
||||
util.exportExcel(response, list, "定时任务");
|
||||
|
|
@ -70,8 +68,7 @@ public class SysJobController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("monitor:job:query")
|
||||
@GetMapping(value = "/{jobId}")
|
||||
public AjaxResult getInfo(@PathVariable("jobId") Long jobId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
|
||||
return success(jobService.selectJobById(jobId));
|
||||
}
|
||||
|
||||
|
|
@ -81,30 +78,18 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:add")
|
||||
@Log(title = "定时任务", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException
|
||||
{
|
||||
if (!CronUtils.isValid(job.getCronExpression()))
|
||||
{
|
||||
public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException {
|
||||
if (!CronUtils.isValid(job.getCronExpression())) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,Cron表达式不正确");
|
||||
}
|
||||
else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI))
|
||||
{
|
||||
} else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS }))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS }))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,目标字符串存在违规");
|
||||
}
|
||||
else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
|
||||
{
|
||||
} else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
|
||||
return error("新增任务'" + job.getJobName() + "'失败,目标字符串不在白名单内");
|
||||
}
|
||||
job.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -117,30 +102,18 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:edit")
|
||||
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException
|
||||
{
|
||||
if (!CronUtils.isValid(job.getCronExpression()))
|
||||
{
|
||||
public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
|
||||
if (!CronUtils.isValid(job.getCronExpression())) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,Cron表达式不正确");
|
||||
}
|
||||
else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI))
|
||||
{
|
||||
} else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS }))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS }))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用");
|
||||
}
|
||||
else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR))
|
||||
{
|
||||
} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,目标字符串存在违规");
|
||||
}
|
||||
else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
|
||||
{
|
||||
} else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
|
||||
return error("修改任务'" + job.getJobName() + "'失败,目标字符串不在白名单内");
|
||||
}
|
||||
job.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -153,8 +126,7 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:changeStatus")
|
||||
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/changeStatus")
|
||||
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException
|
||||
{
|
||||
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
|
||||
SysJob newJob = jobService.selectJobById(job.getJobId());
|
||||
newJob.setStatus(job.getStatus());
|
||||
return toAjax(jobService.changeStatus(newJob));
|
||||
|
|
@ -166,8 +138,7 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:changeStatus")
|
||||
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/run")
|
||||
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException
|
||||
{
|
||||
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException {
|
||||
boolean result = jobService.run(job);
|
||||
return result ? success() : error("任务不存在或已过期!");
|
||||
}
|
||||
|
|
@ -178,8 +149,7 @@ public class SysJobController extends BaseController
|
|||
@RequiresPermissions("monitor:job:remove")
|
||||
@Log(title = "定时任务", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{jobIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
|
||||
jobService.deleteJobByIds(jobIds);
|
||||
return success();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.job.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
|
@ -21,13 +22,12 @@ import com.ruoyi.job.service.ISysJobLogService;
|
|||
|
||||
/**
|
||||
* 调度日志操作处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/job/log")
|
||||
public class SysJobLogController extends BaseController
|
||||
{
|
||||
public class SysJobLogController extends BaseController {
|
||||
@Autowired
|
||||
private ISysJobLogService jobLogService;
|
||||
|
||||
|
|
@ -36,8 +36,7 @@ public class SysJobLogController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("monitor:job:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysJobLog sysJobLog)
|
||||
{
|
||||
public TableDataInfo list(SysJobLog sysJobLog) {
|
||||
startPage();
|
||||
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
|
||||
return getDataTable(list);
|
||||
|
|
@ -49,8 +48,7 @@ public class SysJobLogController extends BaseController
|
|||
@RequiresPermissions("monitor:job:export")
|
||||
@Log(title = "任务调度日志", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysJobLog sysJobLog)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysJobLog sysJobLog) {
|
||||
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
|
||||
ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class);
|
||||
util.exportExcel(response, list, "调度日志");
|
||||
|
|
@ -61,8 +59,7 @@ public class SysJobLogController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("monitor:job:query")
|
||||
@GetMapping(value = "/{jobLogId}")
|
||||
public AjaxResult getInfo(@PathVariable Long jobLogId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long jobLogId) {
|
||||
return success(jobLogService.selectJobLogById(jobLogId));
|
||||
}
|
||||
|
||||
|
|
@ -72,8 +69,7 @@ public class SysJobLogController extends BaseController
|
|||
@RequiresPermissions("monitor:job:remove")
|
||||
@Log(title = "定时任务调度日志", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{jobLogIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] jobLogIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] jobLogIds) {
|
||||
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
|
||||
}
|
||||
|
||||
|
|
@ -83,8 +79,7 @@ public class SysJobLogController extends BaseController
|
|||
@RequiresPermissions("monitor:job:remove")
|
||||
@Log(title = "调度日志", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/clean")
|
||||
public AjaxResult clean()
|
||||
{
|
||||
public AjaxResult clean() {
|
||||
jobLogService.cleanJobLog();
|
||||
return success();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package com.ruoyi.job.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.Date;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
|
@ -15,157 +17,155 @@ import com.ruoyi.job.util.CronUtils;
|
|||
|
||||
/**
|
||||
* 定时任务调度表 sys_job
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SysJob extends BaseEntity
|
||||
{
|
||||
public class SysJob extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 任务ID */
|
||||
/**
|
||||
* 任务ID
|
||||
*/
|
||||
@Excel(name = "任务序号", cellType = ColumnType.NUMERIC)
|
||||
private Long jobId;
|
||||
|
||||
/** 任务名称 */
|
||||
/**
|
||||
* 任务名称
|
||||
*/
|
||||
@Excel(name = "任务名称")
|
||||
private String jobName;
|
||||
|
||||
/** 任务组名 */
|
||||
/**
|
||||
* 任务组名
|
||||
*/
|
||||
@Excel(name = "任务组名")
|
||||
private String jobGroup;
|
||||
|
||||
/** 调用目标字符串 */
|
||||
/**
|
||||
* 调用目标字符串
|
||||
*/
|
||||
@Excel(name = "调用目标字符串")
|
||||
private String invokeTarget;
|
||||
|
||||
/** cron执行表达式 */
|
||||
/**
|
||||
* cron执行表达式
|
||||
*/
|
||||
@Excel(name = "执行表达式 ")
|
||||
private String cronExpression;
|
||||
|
||||
/** cron计划策略 */
|
||||
/**
|
||||
* cron计划策略
|
||||
*/
|
||||
@Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行")
|
||||
private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;
|
||||
|
||||
/** 是否并发执行(0允许 1禁止) */
|
||||
/**
|
||||
* 是否并发执行(0允许 1禁止)
|
||||
*/
|
||||
@Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止")
|
||||
private String concurrent;
|
||||
|
||||
/** 任务状态(0正常 1暂停) */
|
||||
/**
|
||||
* 任务状态(0正常 1暂停)
|
||||
*/
|
||||
@Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停")
|
||||
private String status;
|
||||
|
||||
public Long getJobId()
|
||||
{
|
||||
public Long getJobId() {
|
||||
return jobId;
|
||||
}
|
||||
|
||||
public void setJobId(Long jobId)
|
||||
{
|
||||
public void setJobId(Long jobId) {
|
||||
this.jobId = jobId;
|
||||
}
|
||||
|
||||
@NotBlank(message = "任务名称不能为空")
|
||||
@Size(min = 0, max = 64, message = "任务名称不能超过64个字符")
|
||||
public String getJobName()
|
||||
{
|
||||
public String getJobName() {
|
||||
return jobName;
|
||||
}
|
||||
|
||||
public void setJobName(String jobName)
|
||||
{
|
||||
public void setJobName(String jobName) {
|
||||
this.jobName = jobName;
|
||||
}
|
||||
|
||||
public String getJobGroup()
|
||||
{
|
||||
public String getJobGroup() {
|
||||
return jobGroup;
|
||||
}
|
||||
|
||||
public void setJobGroup(String jobGroup)
|
||||
{
|
||||
public void setJobGroup(String jobGroup) {
|
||||
this.jobGroup = jobGroup;
|
||||
}
|
||||
|
||||
@NotBlank(message = "调用目标字符串不能为空")
|
||||
@Size(min = 0, max = 500, message = "调用目标字符串长度不能超过500个字符")
|
||||
public String getInvokeTarget()
|
||||
{
|
||||
public String getInvokeTarget() {
|
||||
return invokeTarget;
|
||||
}
|
||||
|
||||
public void setInvokeTarget(String invokeTarget)
|
||||
{
|
||||
public void setInvokeTarget(String invokeTarget) {
|
||||
this.invokeTarget = invokeTarget;
|
||||
}
|
||||
|
||||
@NotBlank(message = "Cron执行表达式不能为空")
|
||||
@Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符")
|
||||
public String getCronExpression()
|
||||
{
|
||||
public String getCronExpression() {
|
||||
return cronExpression;
|
||||
}
|
||||
|
||||
public void setCronExpression(String cronExpression)
|
||||
{
|
||||
public void setCronExpression(String cronExpression) {
|
||||
this.cronExpression = cronExpression;
|
||||
}
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public Date getNextValidTime()
|
||||
{
|
||||
if (StringUtils.isNotEmpty(cronExpression))
|
||||
{
|
||||
public Date getNextValidTime() {
|
||||
if (StringUtils.isNotEmpty(cronExpression)) {
|
||||
return CronUtils.getNextExecution(cronExpression);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMisfirePolicy()
|
||||
{
|
||||
public String getMisfirePolicy() {
|
||||
return misfirePolicy;
|
||||
}
|
||||
|
||||
public void setMisfirePolicy(String misfirePolicy)
|
||||
{
|
||||
public void setMisfirePolicy(String misfirePolicy) {
|
||||
this.misfirePolicy = misfirePolicy;
|
||||
}
|
||||
|
||||
public String getConcurrent()
|
||||
{
|
||||
public String getConcurrent() {
|
||||
return concurrent;
|
||||
}
|
||||
|
||||
public void setConcurrent(String concurrent)
|
||||
{
|
||||
public void setConcurrent(String concurrent) {
|
||||
this.concurrent = concurrent;
|
||||
}
|
||||
|
||||
public String getStatus()
|
||||
{
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status)
|
||||
{
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("jobId", getJobId())
|
||||
.append("jobName", getJobName())
|
||||
.append("jobGroup", getJobGroup())
|
||||
.append("cronExpression", getCronExpression())
|
||||
.append("nextValidTime", getNextValidTime())
|
||||
.append("misfirePolicy", getMisfirePolicy())
|
||||
.append("concurrent", getConcurrent())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("jobId", getJobId())
|
||||
.append("jobName", getJobName())
|
||||
.append("jobGroup", getJobGroup())
|
||||
.append("cronExpression", getCronExpression())
|
||||
.append("nextValidTime", getNextValidTime())
|
||||
.append("misfirePolicy", getMisfirePolicy())
|
||||
.append("concurrent", getConcurrent())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.job.service;
|
||||
|
||||
import java.util.List;
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.quartz.JobDataMap;
|
||||
import org.quartz.JobKey;
|
||||
import org.quartz.Scheduler;
|
||||
|
|
@ -18,12 +19,11 @@ import com.ruoyi.job.util.ScheduleUtils;
|
|||
|
||||
/**
|
||||
* 定时任务调度信息 服务层
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class SysJobServiceImpl implements ISysJobService
|
||||
{
|
||||
public class SysJobServiceImpl implements ISysJobService {
|
||||
@Autowired
|
||||
private Scheduler scheduler;
|
||||
|
||||
|
|
@ -34,55 +34,48 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
* 项目启动时,初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据)
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() throws SchedulerException, TaskException
|
||||
{
|
||||
public void init() throws SchedulerException, TaskException {
|
||||
scheduler.clear();
|
||||
List<SysJob> jobList = jobMapper.selectJobAll();
|
||||
for (SysJob job : jobList)
|
||||
{
|
||||
for (SysJob job : jobList) {
|
||||
ScheduleUtils.createScheduleJob(scheduler, job);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取quartz调度器的计划任务列表
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<SysJob> selectJobList(SysJob job)
|
||||
{
|
||||
public List<SysJob> selectJobList(SysJob job) {
|
||||
return jobMapper.selectJobList(job);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过调度任务ID查询调度信息
|
||||
*
|
||||
*
|
||||
* @param jobId 调度任务ID
|
||||
* @return 调度任务对象信息
|
||||
*/
|
||||
@Override
|
||||
public SysJob selectJobById(Long jobId)
|
||||
{
|
||||
public SysJob selectJobById(Long jobId) {
|
||||
return jobMapper.selectJobById(jobId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停任务
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int pauseJob(SysJob job) throws SchedulerException
|
||||
{
|
||||
public int pauseJob(SysJob job) throws SchedulerException {
|
||||
Long jobId = job.getJobId();
|
||||
String jobGroup = job.getJobGroup();
|
||||
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
|
||||
int rows = jobMapper.updateJob(job);
|
||||
if (rows > 0)
|
||||
{
|
||||
if (rows > 0) {
|
||||
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -90,19 +83,17 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 恢复任务
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int resumeJob(SysJob job) throws SchedulerException
|
||||
{
|
||||
public int resumeJob(SysJob job) throws SchedulerException {
|
||||
Long jobId = job.getJobId();
|
||||
String jobGroup = job.getJobGroup();
|
||||
job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
|
||||
int rows = jobMapper.updateJob(job);
|
||||
if (rows > 0)
|
||||
{
|
||||
if (rows > 0) {
|
||||
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -110,18 +101,16 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 删除任务后,所对应的trigger也将被删除
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int deleteJob(SysJob job) throws SchedulerException
|
||||
{
|
||||
public int deleteJob(SysJob job) throws SchedulerException {
|
||||
Long jobId = job.getJobId();
|
||||
String jobGroup = job.getJobGroup();
|
||||
int rows = jobMapper.deleteJobById(jobId);
|
||||
if (rows > 0)
|
||||
{
|
||||
if (rows > 0) {
|
||||
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -129,16 +118,13 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 批量删除调度信息
|
||||
*
|
||||
*
|
||||
* @param jobIds 需要删除的任务ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteJobByIds(Long[] jobIds) throws SchedulerException
|
||||
{
|
||||
for (Long jobId : jobIds)
|
||||
{
|
||||
public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
|
||||
for (Long jobId : jobIds) {
|
||||
SysJob job = jobMapper.selectJobById(jobId);
|
||||
deleteJob(job);
|
||||
}
|
||||
|
|
@ -146,21 +132,17 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 任务调度状态修改
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int changeStatus(SysJob job) throws SchedulerException
|
||||
{
|
||||
public int changeStatus(SysJob job) throws SchedulerException {
|
||||
int rows = 0;
|
||||
String status = job.getStatus();
|
||||
if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
|
||||
{
|
||||
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
|
||||
rows = resumeJob(job);
|
||||
}
|
||||
else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
|
||||
{
|
||||
} else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
|
||||
rows = pauseJob(job);
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -168,13 +150,12 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 立即运行任务
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean run(SysJob job) throws SchedulerException
|
||||
{
|
||||
public boolean run(SysJob job) throws SchedulerException {
|
||||
boolean result = false;
|
||||
Long jobId = job.getJobId();
|
||||
String jobGroup = job.getJobGroup();
|
||||
|
|
@ -183,8 +164,7 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
JobDataMap dataMap = new JobDataMap();
|
||||
dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
|
||||
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
|
||||
if (scheduler.checkExists(jobKey))
|
||||
{
|
||||
if (scheduler.checkExists(jobKey)) {
|
||||
result = true;
|
||||
scheduler.triggerJob(jobKey, dataMap);
|
||||
}
|
||||
|
|
@ -193,17 +173,15 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 新增任务
|
||||
*
|
||||
*
|
||||
* @param job 调度信息 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int insertJob(SysJob job) throws SchedulerException, TaskException
|
||||
{
|
||||
public int insertJob(SysJob job) throws SchedulerException, TaskException {
|
||||
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
|
||||
int rows = jobMapper.insertJob(job);
|
||||
if (rows > 0)
|
||||
{
|
||||
if (rows > 0) {
|
||||
ScheduleUtils.createScheduleJob(scheduler, job);
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -211,17 +189,15 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 更新任务的时间表达式
|
||||
*
|
||||
*
|
||||
* @param job 调度信息
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateJob(SysJob job) throws SchedulerException, TaskException
|
||||
{
|
||||
public int updateJob(SysJob job) throws SchedulerException, TaskException {
|
||||
SysJob properties = selectJobById(job.getJobId());
|
||||
int rows = jobMapper.updateJob(job);
|
||||
if (rows > 0)
|
||||
{
|
||||
if (rows > 0) {
|
||||
updateSchedulerJob(job, properties.getJobGroup());
|
||||
}
|
||||
return rows;
|
||||
|
|
@ -229,17 +205,15 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 更新任务
|
||||
*
|
||||
* @param job 任务对象
|
||||
*
|
||||
* @param job 任务对象
|
||||
* @param jobGroup 任务组名
|
||||
*/
|
||||
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
|
||||
{
|
||||
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
|
||||
Long jobId = job.getJobId();
|
||||
// 判断是否存在
|
||||
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
|
||||
if (scheduler.checkExists(jobKey))
|
||||
{
|
||||
if (scheduler.checkExists(jobKey)) {
|
||||
// 防止创建时存在数据问题 先移除,然后在执行创建操作
|
||||
scheduler.deleteJob(jobKey);
|
||||
}
|
||||
|
|
@ -248,13 +222,12 @@ public class SysJobServiceImpl implements ISysJobService
|
|||
|
||||
/**
|
||||
* 校验cron表达式是否有效
|
||||
*
|
||||
*
|
||||
* @param cronExpression 表达式
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean checkCronExpressionIsValid(String cronExpression)
|
||||
{
|
||||
public boolean checkCronExpressionIsValid(String cronExpression) {
|
||||
return CronUtils.isValid(cronExpression);
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,12 @@
|
|||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- 更新nacos-client到最新 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-client</artifactId>
|
||||
<version>${nacos-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
|
|
@ -40,14 +46,18 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Swagger UI -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.springfox</groupId>-->
|
||||
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
|
||||
<!-- <version>${swagger.fox.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Mysql Connector -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.ruoyi.system;
|
||||
|
||||
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import com.ruoyi.common.security.annotation.EnableCustomConfig;
|
||||
|
|
@ -8,27 +9,16 @@ import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
|
|||
|
||||
/**
|
||||
* 系统模块
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@EnableCustomConfig
|
||||
@EnableCustomSwagger2
|
||||
@EnableRyFeignClients
|
||||
@SpringBootApplication
|
||||
public class RuoYiSystemApplication
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
|
||||
public class RuoYiSystemApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RuoYiSystemApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
" | ( ' ) | \\ _. / ' \n" +
|
||||
" |(_ o _) / _( )_ .' \n" +
|
||||
" | (_,_).' __ ___(_ o _)' \n" +
|
||||
" | |\\ \\ | || |(_,_)' \n" +
|
||||
" | | \\ `' /| `-' / \n" +
|
||||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -25,13 +26,12 @@ import com.ruoyi.system.service.ISysConfigService;
|
|||
|
||||
/**
|
||||
* 参数配置 信息操作处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/config")
|
||||
public class SysConfigController extends BaseController
|
||||
{
|
||||
public class SysConfigController extends BaseController {
|
||||
@Autowired
|
||||
private ISysConfigService configService;
|
||||
|
||||
|
|
@ -40,8 +40,7 @@ public class SysConfigController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:config:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysConfig config)
|
||||
{
|
||||
public TableDataInfo list(SysConfig config) {
|
||||
startPage();
|
||||
List<SysConfig> list = configService.selectConfigList(config);
|
||||
return getDataTable(list);
|
||||
|
|
@ -50,10 +49,9 @@ public class SysConfigController extends BaseController
|
|||
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:config:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysConfig config)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysConfig config) {
|
||||
List<SysConfig> list = configService.selectConfigList(config);
|
||||
ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
|
||||
ExcelUtil<SysConfig> util = new ExcelUtil<>(SysConfig.class);
|
||||
util.exportExcel(response, list, "参数数据");
|
||||
}
|
||||
|
||||
|
|
@ -61,8 +59,7 @@ public class SysConfigController extends BaseController
|
|||
* 根据参数编号获取详细信息
|
||||
*/
|
||||
@GetMapping(value = "/{configId}")
|
||||
public AjaxResult getInfo(@PathVariable Long configId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long configId) {
|
||||
return success(configService.selectConfigById(configId));
|
||||
}
|
||||
|
||||
|
|
@ -70,8 +67,7 @@ public class SysConfigController extends BaseController
|
|||
* 根据参数键名查询参数值
|
||||
*/
|
||||
@GetMapping(value = "/configKey/{configKey}")
|
||||
public AjaxResult getConfigKey(@PathVariable String configKey)
|
||||
{
|
||||
public AjaxResult getConfigKey(@PathVariable String configKey) {
|
||||
return success(configService.selectConfigByKey(configKey));
|
||||
}
|
||||
|
||||
|
|
@ -81,10 +77,8 @@ public class SysConfigController extends BaseController
|
|||
@RequiresPermissions("system:config:add")
|
||||
@Log(title = "参数管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysConfig config)
|
||||
{
|
||||
if (!configService.checkConfigKeyUnique(config))
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysConfig config) {
|
||||
if (!configService.checkConfigKeyUnique(config)) {
|
||||
return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
|
||||
}
|
||||
config.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -97,10 +91,8 @@ public class SysConfigController extends BaseController
|
|||
@RequiresPermissions("system:config:edit")
|
||||
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysConfig config)
|
||||
{
|
||||
if (!configService.checkConfigKeyUnique(config))
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysConfig config) {
|
||||
if (!configService.checkConfigKeyUnique(config)) {
|
||||
return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
|
||||
}
|
||||
config.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -113,8 +105,7 @@ public class SysConfigController extends BaseController
|
|||
@RequiresPermissions("system:config:remove")
|
||||
@Log(title = "参数管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{configIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] configIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] configIds) {
|
||||
configService.deleteConfigByIds(configIds);
|
||||
return success();
|
||||
}
|
||||
|
|
@ -125,8 +116,7 @@ public class SysConfigController extends BaseController
|
|||
@RequiresPermissions("system:config:remove")
|
||||
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/refreshCache")
|
||||
public AjaxResult refreshCache()
|
||||
{
|
||||
public AjaxResult refreshCache() {
|
||||
configService.resetConfigCache();
|
||||
return success();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@ package com.ruoyi.system.controller;
|
|||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -28,23 +29,21 @@ import com.ruoyi.system.service.ISysDictTypeService;
|
|||
|
||||
/**
|
||||
* 数据字典信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/dict/data")
|
||||
public class SysDictDataController extends BaseController
|
||||
{
|
||||
public class SysDictDataController extends BaseController {
|
||||
@Autowired
|
||||
private ISysDictDataService dictDataService;
|
||||
|
||||
|
||||
@Autowired
|
||||
private ISysDictTypeService dictTypeService;
|
||||
|
||||
@RequiresPermissions("system:dict:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysDictData dictData)
|
||||
{
|
||||
public TableDataInfo list(SysDictData dictData) {
|
||||
startPage();
|
||||
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
|
||||
return getDataTable(list);
|
||||
|
|
@ -53,8 +52,7 @@ public class SysDictDataController extends BaseController
|
|||
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:dict:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysDictData dictData)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysDictData dictData) {
|
||||
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
|
||||
ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
|
||||
util.exportExcel(response, list, "字典数据");
|
||||
|
|
@ -65,8 +63,7 @@ public class SysDictDataController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:dict:query")
|
||||
@GetMapping(value = "/{dictCode}")
|
||||
public AjaxResult getInfo(@PathVariable Long dictCode)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long dictCode) {
|
||||
return success(dictDataService.selectDictDataById(dictCode));
|
||||
}
|
||||
|
||||
|
|
@ -74,11 +71,9 @@ public class SysDictDataController extends BaseController
|
|||
* 根据字典类型查询字典数据信息
|
||||
*/
|
||||
@GetMapping(value = "/type/{dictType}")
|
||||
public AjaxResult dictType(@PathVariable String dictType)
|
||||
{
|
||||
public AjaxResult dictType(@PathVariable String dictType) {
|
||||
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
|
||||
if (StringUtils.isNull(data))
|
||||
{
|
||||
if (StringUtils.isNull(data)) {
|
||||
data = new ArrayList<SysDictData>();
|
||||
}
|
||||
return success(data);
|
||||
|
|
@ -90,8 +85,7 @@ public class SysDictDataController extends BaseController
|
|||
@RequiresPermissions("system:dict:add")
|
||||
@Log(title = "字典数据", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysDictData dict)
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysDictData dict) {
|
||||
dict.setCreateBy(SecurityUtils.getUsername());
|
||||
return toAjax(dictDataService.insertDictData(dict));
|
||||
}
|
||||
|
|
@ -102,8 +96,7 @@ public class SysDictDataController extends BaseController
|
|||
@RequiresPermissions("system:dict:edit")
|
||||
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysDictData dict)
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysDictData dict) {
|
||||
dict.setUpdateBy(SecurityUtils.getUsername());
|
||||
return toAjax(dictDataService.updateDictData(dict));
|
||||
}
|
||||
|
|
@ -114,8 +107,7 @@ public class SysDictDataController extends BaseController
|
|||
@RequiresPermissions("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{dictCodes}")
|
||||
public AjaxResult remove(@PathVariable Long[] dictCodes)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] dictCodes) {
|
||||
dictDataService.deleteDictDataByIds(dictCodes);
|
||||
return success();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -25,20 +26,18 @@ import com.ruoyi.system.service.ISysDictTypeService;
|
|||
|
||||
/**
|
||||
* 数据字典信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/dict/type")
|
||||
public class SysDictTypeController extends BaseController
|
||||
{
|
||||
public class SysDictTypeController extends BaseController {
|
||||
@Autowired
|
||||
private ISysDictTypeService dictTypeService;
|
||||
|
||||
@RequiresPermissions("system:dict:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysDictType dictType)
|
||||
{
|
||||
public TableDataInfo list(SysDictType dictType) {
|
||||
startPage();
|
||||
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
|
||||
return getDataTable(list);
|
||||
|
|
@ -47,10 +46,9 @@ public class SysDictTypeController extends BaseController
|
|||
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:dict:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysDictType dictType)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysDictType dictType) {
|
||||
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
|
||||
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
|
||||
ExcelUtil<SysDictType> util = new ExcelUtil<>(SysDictType.class);
|
||||
util.exportExcel(response, list, "字典类型");
|
||||
}
|
||||
|
||||
|
|
@ -59,8 +57,7 @@ public class SysDictTypeController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:dict:query")
|
||||
@GetMapping(value = "/{dictId}")
|
||||
public AjaxResult getInfo(@PathVariable Long dictId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long dictId) {
|
||||
return success(dictTypeService.selectDictTypeById(dictId));
|
||||
}
|
||||
|
||||
|
|
@ -70,10 +67,8 @@ public class SysDictTypeController extends BaseController
|
|||
@RequiresPermissions("system:dict:add")
|
||||
@Log(title = "字典类型", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysDictType dict)
|
||||
{
|
||||
if (!dictTypeService.checkDictTypeUnique(dict))
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysDictType dict) {
|
||||
if (!dictTypeService.checkDictTypeUnique(dict)) {
|
||||
return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
|
||||
}
|
||||
dict.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -86,10 +81,8 @@ public class SysDictTypeController extends BaseController
|
|||
@RequiresPermissions("system:dict:edit")
|
||||
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysDictType dict)
|
||||
{
|
||||
if (!dictTypeService.checkDictTypeUnique(dict))
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysDictType dict) {
|
||||
if (!dictTypeService.checkDictTypeUnique(dict)) {
|
||||
return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
|
||||
}
|
||||
dict.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -102,8 +95,7 @@ public class SysDictTypeController extends BaseController
|
|||
@RequiresPermissions("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{dictIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] dictIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] dictIds) {
|
||||
dictTypeService.deleteDictTypeByIds(dictIds);
|
||||
return success();
|
||||
}
|
||||
|
|
@ -114,8 +106,7 @@ public class SysDictTypeController extends BaseController
|
|||
@RequiresPermissions("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/refreshCache")
|
||||
public AjaxResult refreshCache()
|
||||
{
|
||||
public AjaxResult refreshCache() {
|
||||
dictTypeService.resetDictCache();
|
||||
return success();
|
||||
}
|
||||
|
|
@ -124,8 +115,7 @@ public class SysDictTypeController extends BaseController
|
|||
* 获取字典选择框列表
|
||||
*/
|
||||
@GetMapping("/optionselect")
|
||||
public AjaxResult optionselect()
|
||||
{
|
||||
public AjaxResult optionselect() {
|
||||
List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
|
||||
return success(dictTypes);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
|
@ -25,13 +26,12 @@ import com.ruoyi.system.service.ISysLogininforService;
|
|||
|
||||
/**
|
||||
* 系统访问记录
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/logininfor")
|
||||
public class SysLogininforController extends BaseController
|
||||
{
|
||||
public class SysLogininforController extends BaseController {
|
||||
@Autowired
|
||||
private ISysLogininforService logininforService;
|
||||
|
||||
|
|
@ -40,8 +40,7 @@ public class SysLogininforController extends BaseController
|
|||
|
||||
@RequiresPermissions("system:logininfor:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysLogininfor logininfor)
|
||||
{
|
||||
public TableDataInfo list(SysLogininfor logininfor) {
|
||||
startPage();
|
||||
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
|
||||
return getDataTable(list);
|
||||
|
|
@ -50,26 +49,23 @@ public class SysLogininforController extends BaseController
|
|||
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:logininfor:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysLogininfor logininfor)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysLogininfor logininfor) {
|
||||
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
|
||||
ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class);
|
||||
ExcelUtil<SysLogininfor> util = new ExcelUtil<>(SysLogininfor.class);
|
||||
util.exportExcel(response, list, "登录日志");
|
||||
}
|
||||
|
||||
@RequiresPermissions("system:logininfor:remove")
|
||||
@Log(title = "登录日志", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{infoIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] infoIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] infoIds) {
|
||||
return toAjax(logininforService.deleteLogininforByIds(infoIds));
|
||||
}
|
||||
|
||||
@RequiresPermissions("system:logininfor:remove")
|
||||
@Log(title = "登录日志", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/clean")
|
||||
public AjaxResult clean()
|
||||
{
|
||||
public AjaxResult clean() {
|
||||
logininforService.cleanLogininfor();
|
||||
return success();
|
||||
}
|
||||
|
|
@ -77,16 +73,14 @@ public class SysLogininforController extends BaseController
|
|||
@RequiresPermissions("system:logininfor:unlock")
|
||||
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
|
||||
@GetMapping("/unlock/{userName}")
|
||||
public AjaxResult unlock(@PathVariable("userName") String userName)
|
||||
{
|
||||
public AjaxResult unlock(@PathVariable("userName") String userName) {
|
||||
redisService.deleteObject(CacheConstants.PWD_ERR_CNT_KEY + userName);
|
||||
return success();
|
||||
}
|
||||
|
||||
@InnerAuth
|
||||
@PostMapping
|
||||
public AjaxResult add(@RequestBody SysLogininfor logininfor)
|
||||
{
|
||||
public AjaxResult add(@RequestBody SysLogininfor logininfor) {
|
||||
return toAjax(logininforService.insertLogininfor(logininfor));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
|
@ -23,20 +24,18 @@ import com.ruoyi.system.service.ISysOperLogService;
|
|||
|
||||
/**
|
||||
* 操作日志记录
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/operlog")
|
||||
public class SysOperlogController extends BaseController
|
||||
{
|
||||
public class SysOperlogController extends BaseController {
|
||||
@Autowired
|
||||
private ISysOperLogService operLogService;
|
||||
|
||||
@RequiresPermissions("system:operlog:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysOperLog operLog)
|
||||
{
|
||||
public TableDataInfo list(SysOperLog operLog) {
|
||||
startPage();
|
||||
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
|
||||
return getDataTable(list);
|
||||
|
|
@ -45,8 +44,7 @@ public class SysOperlogController extends BaseController
|
|||
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:operlog:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysOperLog operLog)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysOperLog operLog) {
|
||||
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
|
||||
ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
|
||||
util.exportExcel(response, list, "操作日志");
|
||||
|
|
@ -55,24 +53,21 @@ public class SysOperlogController extends BaseController
|
|||
@Log(title = "操作日志", businessType = BusinessType.DELETE)
|
||||
@RequiresPermissions("system:operlog:remove")
|
||||
@DeleteMapping("/{operIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] operIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] operIds) {
|
||||
return toAjax(operLogService.deleteOperLogByIds(operIds));
|
||||
}
|
||||
|
||||
@RequiresPermissions("system:operlog:remove")
|
||||
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/clean")
|
||||
public AjaxResult clean()
|
||||
{
|
||||
public AjaxResult clean() {
|
||||
operLogService.cleanOperLog();
|
||||
return success();
|
||||
}
|
||||
|
||||
@InnerAuth
|
||||
@PostMapping
|
||||
public AjaxResult add(@RequestBody SysOperLog operLog)
|
||||
{
|
||||
public AjaxResult add(@RequestBody SysOperLog operLog) {
|
||||
return toAjax(operLogService.insertOperlog(operLog));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -25,13 +26,12 @@ import com.ruoyi.system.service.ISysPostService;
|
|||
|
||||
/**
|
||||
* 岗位信息操作处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/post")
|
||||
public class SysPostController extends BaseController
|
||||
{
|
||||
public class SysPostController extends BaseController {
|
||||
@Autowired
|
||||
private ISysPostService postService;
|
||||
|
||||
|
|
@ -40,8 +40,7 @@ public class SysPostController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:post:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysPost post)
|
||||
{
|
||||
public TableDataInfo list(SysPost post) {
|
||||
startPage();
|
||||
List<SysPost> list = postService.selectPostList(post);
|
||||
return getDataTable(list);
|
||||
|
|
@ -50,10 +49,9 @@ public class SysPostController extends BaseController
|
|||
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:post:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysPost post)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysPost post) {
|
||||
List<SysPost> list = postService.selectPostList(post);
|
||||
ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
|
||||
ExcelUtil<SysPost> util = new ExcelUtil<>(SysPost.class);
|
||||
util.exportExcel(response, list, "岗位数据");
|
||||
}
|
||||
|
||||
|
|
@ -62,8 +60,7 @@ public class SysPostController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:post:query")
|
||||
@GetMapping(value = "/{postId}")
|
||||
public AjaxResult getInfo(@PathVariable Long postId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long postId) {
|
||||
return success(postService.selectPostById(postId));
|
||||
}
|
||||
|
||||
|
|
@ -73,14 +70,10 @@ public class SysPostController extends BaseController
|
|||
@RequiresPermissions("system:post:add")
|
||||
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysPost post)
|
||||
{
|
||||
if (!postService.checkPostNameUnique(post))
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysPost post) {
|
||||
if (!postService.checkPostNameUnique(post)) {
|
||||
return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
|
||||
}
|
||||
else if (!postService.checkPostCodeUnique(post))
|
||||
{
|
||||
} else if (!postService.checkPostCodeUnique(post)) {
|
||||
return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
|
||||
}
|
||||
post.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -93,14 +86,10 @@ public class SysPostController extends BaseController
|
|||
@RequiresPermissions("system:post:edit")
|
||||
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysPost post)
|
||||
{
|
||||
if (!postService.checkPostNameUnique(post))
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysPost post) {
|
||||
if (!postService.checkPostNameUnique(post)) {
|
||||
return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
|
||||
}
|
||||
else if (!postService.checkPostCodeUnique(post))
|
||||
{
|
||||
} else if (!postService.checkPostCodeUnique(post)) {
|
||||
return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
|
||||
}
|
||||
post.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -113,8 +102,7 @@ public class SysPostController extends BaseController
|
|||
@RequiresPermissions("system:post:remove")
|
||||
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{postIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] postIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] postIds) {
|
||||
return toAjax(postService.deletePostByIds(postIds));
|
||||
}
|
||||
|
||||
|
|
@ -122,8 +110,7 @@ public class SysPostController extends BaseController
|
|||
* 获取岗位选择框列表
|
||||
*/
|
||||
@GetMapping("/optionselect")
|
||||
public AjaxResult optionselect()
|
||||
{
|
||||
public AjaxResult optionselect() {
|
||||
List<SysPost> posts = postService.selectPostAll();
|
||||
return success(posts);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
|
|
@ -30,13 +31,12 @@ import com.ruoyi.system.service.ISysUserService;
|
|||
|
||||
/**
|
||||
* 角色信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/role")
|
||||
public class SysRoleController extends BaseController
|
||||
{
|
||||
public class SysRoleController extends BaseController {
|
||||
@Autowired
|
||||
private ISysRoleService roleService;
|
||||
|
||||
|
|
@ -48,8 +48,7 @@ public class SysRoleController extends BaseController
|
|||
|
||||
@RequiresPermissions("system:role:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysRole role)
|
||||
{
|
||||
public TableDataInfo list(SysRole role) {
|
||||
startPage();
|
||||
List<SysRole> list = roleService.selectRoleList(role);
|
||||
return getDataTable(list);
|
||||
|
|
@ -58,10 +57,9 @@ public class SysRoleController extends BaseController
|
|||
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:role:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysRole role)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysRole role) {
|
||||
List<SysRole> list = roleService.selectRoleList(role);
|
||||
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
|
||||
ExcelUtil<SysRole> util = new ExcelUtil<>(SysRole.class);
|
||||
util.exportExcel(response, list, "角色数据");
|
||||
}
|
||||
|
||||
|
|
@ -70,8 +68,7 @@ public class SysRoleController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:role:query")
|
||||
@GetMapping(value = "/{roleId}")
|
||||
public AjaxResult getInfo(@PathVariable Long roleId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long roleId) {
|
||||
roleService.checkRoleDataScope(roleId);
|
||||
return success(roleService.selectRoleById(roleId));
|
||||
}
|
||||
|
|
@ -82,14 +79,10 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:add")
|
||||
@Log(title = "角色管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysRole role)
|
||||
{
|
||||
if (!roleService.checkRoleNameUnique(role))
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysRole role) {
|
||||
if (!roleService.checkRoleNameUnique(role)) {
|
||||
return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
|
||||
}
|
||||
else if (!roleService.checkRoleKeyUnique(role))
|
||||
{
|
||||
} else if (!roleService.checkRoleKeyUnique(role)) {
|
||||
return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
|
||||
}
|
||||
role.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -103,16 +96,12 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysRole role)
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysRole role) {
|
||||
roleService.checkRoleAllowed(role);
|
||||
roleService.checkRoleDataScope(role.getRoleId());
|
||||
if (!roleService.checkRoleNameUnique(role))
|
||||
{
|
||||
if (!roleService.checkRoleNameUnique(role)) {
|
||||
return error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
|
||||
}
|
||||
else if (!roleService.checkRoleKeyUnique(role))
|
||||
{
|
||||
} else if (!roleService.checkRoleKeyUnique(role)) {
|
||||
return error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
|
||||
}
|
||||
role.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -125,8 +114,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/dataScope")
|
||||
public AjaxResult dataScope(@RequestBody SysRole role)
|
||||
{
|
||||
public AjaxResult dataScope(@RequestBody SysRole role) {
|
||||
roleService.checkRoleAllowed(role);
|
||||
roleService.checkRoleDataScope(role.getRoleId());
|
||||
return toAjax(roleService.authDataScope(role));
|
||||
|
|
@ -138,8 +126,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/changeStatus")
|
||||
public AjaxResult changeStatus(@RequestBody SysRole role)
|
||||
{
|
||||
public AjaxResult changeStatus(@RequestBody SysRole role) {
|
||||
roleService.checkRoleAllowed(role);
|
||||
roleService.checkRoleDataScope(role.getRoleId());
|
||||
role.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -152,8 +139,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:remove")
|
||||
@Log(title = "角色管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{roleIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] roleIds)
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] roleIds) {
|
||||
return toAjax(roleService.deleteRoleByIds(roleIds));
|
||||
}
|
||||
|
||||
|
|
@ -162,17 +148,16 @@ public class SysRoleController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:role:query")
|
||||
@GetMapping("/optionselect")
|
||||
public AjaxResult optionselect()
|
||||
{
|
||||
public AjaxResult optionselect() {
|
||||
return success(roleService.selectRoleAll());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询已分配用户角色列表
|
||||
*/
|
||||
@RequiresPermissions("system:role:list")
|
||||
@GetMapping("/authUser/allocatedList")
|
||||
public TableDataInfo allocatedList(SysUser user)
|
||||
{
|
||||
public TableDataInfo allocatedList(SysUser user) {
|
||||
startPage();
|
||||
List<SysUser> list = userService.selectAllocatedList(user);
|
||||
return getDataTable(list);
|
||||
|
|
@ -183,8 +168,7 @@ public class SysRoleController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:role:list")
|
||||
@GetMapping("/authUser/unallocatedList")
|
||||
public TableDataInfo unallocatedList(SysUser user)
|
||||
{
|
||||
public TableDataInfo unallocatedList(SysUser user) {
|
||||
startPage();
|
||||
List<SysUser> list = userService.selectUnallocatedList(user);
|
||||
return getDataTable(list);
|
||||
|
|
@ -196,8 +180,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.GRANT)
|
||||
@PutMapping("/authUser/cancel")
|
||||
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
|
||||
{
|
||||
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole) {
|
||||
return toAjax(roleService.deleteAuthUser(userRole));
|
||||
}
|
||||
|
||||
|
|
@ -207,8 +190,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.GRANT)
|
||||
@PutMapping("/authUser/cancelAll")
|
||||
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
|
||||
{
|
||||
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) {
|
||||
return toAjax(roleService.deleteAuthUsers(roleId, userIds));
|
||||
}
|
||||
|
||||
|
|
@ -218,8 +200,7 @@ public class SysRoleController extends BaseController
|
|||
@RequiresPermissions("system:role:edit")
|
||||
@Log(title = "角色管理", businessType = BusinessType.GRANT)
|
||||
@PutMapping("/authUser/selectAll")
|
||||
public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
|
||||
{
|
||||
public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) {
|
||||
roleService.checkRoleDataScope(roleId);
|
||||
return toAjax(roleService.insertAuthUsers(roleId, userIds));
|
||||
}
|
||||
|
|
@ -229,8 +210,7 @@ public class SysRoleController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:role:query")
|
||||
@GetMapping(value = "/deptTree/{roleId}")
|
||||
public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
|
||||
{
|
||||
public AjaxResult deptTree(@PathVariable("roleId") Long roleId) {
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
|
||||
ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import java.io.IOException;
|
|||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
|
@ -41,13 +42,12 @@ import com.ruoyi.system.service.ISysUserService;
|
|||
|
||||
/**
|
||||
* 用户信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
public class SysUserController extends BaseController
|
||||
{
|
||||
public class SysUserController extends BaseController {
|
||||
@Autowired
|
||||
private ISysUserService userService;
|
||||
|
||||
|
|
@ -71,8 +71,7 @@ public class SysUserController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:user:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(SysUser user)
|
||||
{
|
||||
public TableDataInfo list(SysUser user) {
|
||||
startPage();
|
||||
List<SysUser> list = userService.selectUserList(user);
|
||||
return getDataTable(list);
|
||||
|
|
@ -81,19 +80,17 @@ public class SysUserController extends BaseController
|
|||
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
|
||||
@RequiresPermissions("system:user:export")
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, SysUser user)
|
||||
{
|
||||
public void export(HttpServletResponse response, SysUser user) {
|
||||
List<SysUser> list = userService.selectUserList(user);
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
|
||||
util.exportExcel(response, list, "用户数据");
|
||||
}
|
||||
|
||||
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
|
||||
@RequiresPermissions("system:user:import")
|
||||
@PostMapping("/importData")
|
||||
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
|
||||
{
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
|
||||
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
|
||||
List<SysUser> userList = util.importExcel(file.getInputStream());
|
||||
String operName = SecurityUtils.getUsername();
|
||||
String message = userService.importUser(userList, updateSupport, operName);
|
||||
|
|
@ -101,9 +98,8 @@ public class SysUserController extends BaseController
|
|||
}
|
||||
|
||||
@PostMapping("/importTemplate")
|
||||
public void importTemplate(HttpServletResponse response) throws IOException
|
||||
{
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
|
||||
public void importTemplate(HttpServletResponse response) {
|
||||
ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
|
||||
util.importTemplateExcel(response, "用户数据");
|
||||
}
|
||||
|
||||
|
|
@ -112,11 +108,9 @@ public class SysUserController extends BaseController
|
|||
*/
|
||||
@InnerAuth
|
||||
@GetMapping("/info/{username}")
|
||||
public R<LoginUser> info(@PathVariable("username") String username)
|
||||
{
|
||||
public R<LoginUser> info(@PathVariable("username") String username) {
|
||||
SysUser sysUser = userService.selectUserByUserName(username);
|
||||
if (StringUtils.isNull(sysUser))
|
||||
{
|
||||
if (StringUtils.isNull(sysUser)) {
|
||||
return R.fail("用户名或密码错误");
|
||||
}
|
||||
// 角色集合
|
||||
|
|
@ -135,15 +129,12 @@ public class SysUserController extends BaseController
|
|||
*/
|
||||
@InnerAuth
|
||||
@PostMapping("/register")
|
||||
public R<Boolean> register(@RequestBody SysUser sysUser)
|
||||
{
|
||||
public R<Boolean> register(@RequestBody SysUser sysUser) {
|
||||
String username = sysUser.getUserName();
|
||||
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
|
||||
{
|
||||
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
|
||||
return R.fail("当前系统没有开启注册功能!");
|
||||
}
|
||||
if (!userService.checkUserNameUnique(sysUser))
|
||||
{
|
||||
if (!userService.checkUserNameUnique(sysUser)) {
|
||||
return R.fail("保存用户'" + username + "'失败,注册账号已存在");
|
||||
}
|
||||
return R.ok(userService.registerUser(sysUser));
|
||||
|
|
@ -151,12 +142,11 @@ public class SysUserController extends BaseController
|
|||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
@GetMapping("getInfo")
|
||||
public AjaxResult getInfo()
|
||||
{
|
||||
public AjaxResult getInfo() {
|
||||
SysUser user = userService.selectUserById(SecurityUtils.getUserId());
|
||||
// 角色集合
|
||||
Set<String> roles = permissionService.getRolePermission(user);
|
||||
|
|
@ -173,16 +163,14 @@ public class SysUserController extends BaseController
|
|||
* 根据用户编号获取详细信息
|
||||
*/
|
||||
@RequiresPermissions("system:user:query")
|
||||
@GetMapping(value = { "/", "/{userId}" })
|
||||
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
|
||||
{
|
||||
@GetMapping(value = {"/", "/{userId}"})
|
||||
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
|
||||
userService.checkUserDataScope(userId);
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
List<SysRole> roles = roleService.selectRoleAll();
|
||||
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
|
||||
ajax.put("posts", postService.selectPostAll());
|
||||
if (StringUtils.isNotNull(userId))
|
||||
{
|
||||
if (StringUtils.isNotNull(userId)) {
|
||||
SysUser sysUser = userService.selectUserById(userId);
|
||||
ajax.put(AjaxResult.DATA_TAG, sysUser);
|
||||
ajax.put("postIds", postService.selectPostListByUserId(userId));
|
||||
|
|
@ -197,18 +185,12 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:add")
|
||||
@Log(title = "用户管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@Validated @RequestBody SysUser user)
|
||||
{
|
||||
if (!userService.checkUserNameUnique(user))
|
||||
{
|
||||
public AjaxResult add(@Validated @RequestBody SysUser user) {
|
||||
if (!userService.checkUserNameUnique(user)) {
|
||||
return error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
|
||||
}
|
||||
else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
|
||||
{
|
||||
} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
|
||||
return error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
|
||||
}
|
||||
else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
|
||||
{
|
||||
} else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
|
||||
return error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
|
||||
}
|
||||
user.setCreateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -222,20 +204,14 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:edit")
|
||||
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public AjaxResult edit(@Validated @RequestBody SysUser user)
|
||||
{
|
||||
public AjaxResult edit(@Validated @RequestBody SysUser user) {
|
||||
userService.checkUserAllowed(user);
|
||||
userService.checkUserDataScope(user.getUserId());
|
||||
if (!userService.checkUserNameUnique(user))
|
||||
{
|
||||
if (!userService.checkUserNameUnique(user)) {
|
||||
return error("修改用户'" + user.getUserName() + "'失败,登录账号已存在");
|
||||
}
|
||||
else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
|
||||
{
|
||||
} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
|
||||
return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
|
||||
}
|
||||
else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
|
||||
{
|
||||
} else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
|
||||
return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
|
||||
}
|
||||
user.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -248,10 +224,8 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:remove")
|
||||
@Log(title = "用户管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{userIds}")
|
||||
public AjaxResult remove(@PathVariable Long[] userIds)
|
||||
{
|
||||
if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
|
||||
{
|
||||
public AjaxResult remove(@PathVariable Long[] userIds) {
|
||||
if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
|
||||
return error("当前用户不能删除");
|
||||
}
|
||||
return toAjax(userService.deleteUserByIds(userIds));
|
||||
|
|
@ -263,8 +237,7 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:edit")
|
||||
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/resetPwd")
|
||||
public AjaxResult resetPwd(@RequestBody SysUser user)
|
||||
{
|
||||
public AjaxResult resetPwd(@RequestBody SysUser user) {
|
||||
userService.checkUserAllowed(user);
|
||||
userService.checkUserDataScope(user.getUserId());
|
||||
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
|
||||
|
|
@ -278,8 +251,7 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:edit")
|
||||
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/changeStatus")
|
||||
public AjaxResult changeStatus(@RequestBody SysUser user)
|
||||
{
|
||||
public AjaxResult changeStatus(@RequestBody SysUser user) {
|
||||
userService.checkUserAllowed(user);
|
||||
userService.checkUserDataScope(user.getUserId());
|
||||
user.setUpdateBy(SecurityUtils.getUsername());
|
||||
|
|
@ -291,8 +263,7 @@ public class SysUserController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:user:query")
|
||||
@GetMapping("/authRole/{userId}")
|
||||
public AjaxResult authRole(@PathVariable("userId") Long userId)
|
||||
{
|
||||
public AjaxResult authRole(@PathVariable("userId") Long userId) {
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
SysUser user = userService.selectUserById(userId);
|
||||
List<SysRole> roles = roleService.selectRolesByUserId(userId);
|
||||
|
|
@ -307,8 +278,7 @@ public class SysUserController extends BaseController
|
|||
@RequiresPermissions("system:user:edit")
|
||||
@Log(title = "用户管理", businessType = BusinessType.GRANT)
|
||||
@PutMapping("/authRole")
|
||||
public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
|
||||
{
|
||||
public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
|
||||
userService.checkUserDataScope(userId);
|
||||
userService.insertUserAuth(userId, roleIds);
|
||||
return success();
|
||||
|
|
@ -319,8 +289,7 @@ public class SysUserController extends BaseController
|
|||
*/
|
||||
@RequiresPermissions("system:user:list")
|
||||
@GetMapping("/deptTree")
|
||||
public AjaxResult deptTree(SysDept dept)
|
||||
{
|
||||
public AjaxResult deptTree(SysDept dept) {
|
||||
return success(deptService.selectDeptTreeList(dept));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
package com.ruoyi.system.controller;
|
||||
|
||||
import com.ruoyi.common.core.web.controller.BaseController;
|
||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* @author Alan Scipio
|
||||
* created on 2024/1/31
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/test")
|
||||
public class TestController extends BaseController {
|
||||
|
||||
@GetMapping("/showInfo")
|
||||
public AjaxResult showInfo() {
|
||||
return success("Hello World!");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,111 +1,113 @@
|
|||
package com.ruoyi.system.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
import com.ruoyi.common.core.annotation.Excel.ColumnType;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 参数配置表 sys_config
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SysConfig extends BaseEntity
|
||||
{
|
||||
public class SysConfig extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 参数主键 */
|
||||
/**
|
||||
* 参数主键
|
||||
*/
|
||||
@Excel(name = "参数主键", cellType = ColumnType.NUMERIC)
|
||||
private Long configId;
|
||||
|
||||
/** 参数名称 */
|
||||
/**
|
||||
* 参数名称
|
||||
*/
|
||||
@Excel(name = "参数名称")
|
||||
private String configName;
|
||||
|
||||
/** 参数键名 */
|
||||
/**
|
||||
* 参数键名
|
||||
*/
|
||||
@Excel(name = "参数键名")
|
||||
private String configKey;
|
||||
|
||||
/** 参数键值 */
|
||||
/**
|
||||
* 参数键值
|
||||
*/
|
||||
@Excel(name = "参数键值")
|
||||
private String configValue;
|
||||
|
||||
/** 系统内置(Y是 N否) */
|
||||
/**
|
||||
* 系统内置(Y是 N否)
|
||||
*/
|
||||
@Excel(name = "系统内置", readConverterExp = "Y=是,N=否")
|
||||
private String configType;
|
||||
|
||||
public Long getConfigId()
|
||||
{
|
||||
public Long getConfigId() {
|
||||
return configId;
|
||||
}
|
||||
|
||||
public void setConfigId(Long configId)
|
||||
{
|
||||
public void setConfigId(Long configId) {
|
||||
this.configId = configId;
|
||||
}
|
||||
|
||||
@NotBlank(message = "参数名称不能为空")
|
||||
@Size(min = 0, max = 100, message = "参数名称不能超过100个字符")
|
||||
public String getConfigName()
|
||||
{
|
||||
public String getConfigName() {
|
||||
return configName;
|
||||
}
|
||||
|
||||
public void setConfigName(String configName)
|
||||
{
|
||||
public void setConfigName(String configName) {
|
||||
this.configName = configName;
|
||||
}
|
||||
|
||||
@NotBlank(message = "参数键名长度不能为空")
|
||||
@Size(min = 0, max = 100, message = "参数键名长度不能超过100个字符")
|
||||
public String getConfigKey()
|
||||
{
|
||||
public String getConfigKey() {
|
||||
return configKey;
|
||||
}
|
||||
|
||||
public void setConfigKey(String configKey)
|
||||
{
|
||||
public void setConfigKey(String configKey) {
|
||||
this.configKey = configKey;
|
||||
}
|
||||
|
||||
@NotBlank(message = "参数键值不能为空")
|
||||
@Size(min = 0, max = 500, message = "参数键值长度不能超过500个字符")
|
||||
public String getConfigValue()
|
||||
{
|
||||
public String getConfigValue() {
|
||||
return configValue;
|
||||
}
|
||||
|
||||
public void setConfigValue(String configValue)
|
||||
{
|
||||
public void setConfigValue(String configValue) {
|
||||
this.configValue = configValue;
|
||||
}
|
||||
|
||||
public String getConfigType()
|
||||
{
|
||||
public String getConfigType() {
|
||||
return configType;
|
||||
}
|
||||
|
||||
public void setConfigType(String configType)
|
||||
{
|
||||
public void setConfigType(String configType) {
|
||||
this.configType = configType;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("configId", getConfigId())
|
||||
.append("configName", getConfigName())
|
||||
.append("configKey", getConfigKey())
|
||||
.append("configValue", getConfigValue())
|
||||
.append("configType", getConfigType())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("configId", getConfigId())
|
||||
.append("configName", getConfigName())
|
||||
.append("configKey", getConfigKey())
|
||||
.append("configValue", getConfigValue())
|
||||
.append("configType", getConfigType())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,259 +1,261 @@
|
|||
package com.ruoyi.system.domain;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* 菜单权限表 sys_menu
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SysMenu extends BaseEntity
|
||||
{
|
||||
public class SysMenu extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 菜单ID */
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
private Long menuId;
|
||||
|
||||
/** 菜单名称 */
|
||||
/**
|
||||
* 菜单名称
|
||||
*/
|
||||
private String menuName;
|
||||
|
||||
/** 父菜单名称 */
|
||||
/**
|
||||
* 父菜单名称
|
||||
*/
|
||||
private String parentName;
|
||||
|
||||
/** 父菜单ID */
|
||||
/**
|
||||
* 父菜单ID
|
||||
*/
|
||||
private Long parentId;
|
||||
|
||||
/** 显示顺序 */
|
||||
/**
|
||||
* 显示顺序
|
||||
*/
|
||||
private Integer orderNum;
|
||||
|
||||
/** 路由地址 */
|
||||
/**
|
||||
* 路由地址
|
||||
*/
|
||||
private String path;
|
||||
|
||||
/** 组件路径 */
|
||||
/**
|
||||
* 组件路径
|
||||
*/
|
||||
private String component;
|
||||
|
||||
/** 路由参数 */
|
||||
/**
|
||||
* 路由参数
|
||||
*/
|
||||
private String query;
|
||||
|
||||
/** 是否为外链(0是 1否) */
|
||||
/**
|
||||
* 是否为外链(0是 1否)
|
||||
*/
|
||||
private String isFrame;
|
||||
|
||||
/** 是否缓存(0缓存 1不缓存) */
|
||||
/**
|
||||
* 是否缓存(0缓存 1不缓存)
|
||||
*/
|
||||
private String isCache;
|
||||
|
||||
/** 类型(M目录 C菜单 F按钮) */
|
||||
/**
|
||||
* 类型(M目录 C菜单 F按钮)
|
||||
*/
|
||||
private String menuType;
|
||||
|
||||
/** 显示状态(0显示 1隐藏) */
|
||||
/**
|
||||
* 显示状态(0显示 1隐藏)
|
||||
*/
|
||||
private String visible;
|
||||
|
||||
/** 菜单状态(0正常 1停用) */
|
||||
|
||||
/**
|
||||
* 菜单状态(0正常 1停用)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/** 权限字符串 */
|
||||
/**
|
||||
* 权限字符串
|
||||
*/
|
||||
private String perms;
|
||||
|
||||
/** 菜单图标 */
|
||||
/**
|
||||
* 菜单图标
|
||||
*/
|
||||
private String icon;
|
||||
|
||||
/** 子菜单 */
|
||||
/**
|
||||
* 子菜单
|
||||
*/
|
||||
private List<SysMenu> children = new ArrayList<SysMenu>();
|
||||
|
||||
public Long getMenuId()
|
||||
{
|
||||
public Long getMenuId() {
|
||||
return menuId;
|
||||
}
|
||||
|
||||
public void setMenuId(Long menuId)
|
||||
{
|
||||
public void setMenuId(Long menuId) {
|
||||
this.menuId = menuId;
|
||||
}
|
||||
|
||||
@NotBlank(message = "菜单名称不能为空")
|
||||
@Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符")
|
||||
public String getMenuName()
|
||||
{
|
||||
public String getMenuName() {
|
||||
return menuName;
|
||||
}
|
||||
|
||||
public void setMenuName(String menuName)
|
||||
{
|
||||
public void setMenuName(String menuName) {
|
||||
this.menuName = menuName;
|
||||
}
|
||||
|
||||
public String getParentName()
|
||||
{
|
||||
public String getParentName() {
|
||||
return parentName;
|
||||
}
|
||||
|
||||
public void setParentName(String parentName)
|
||||
{
|
||||
public void setParentName(String parentName) {
|
||||
this.parentName = parentName;
|
||||
}
|
||||
|
||||
public Long getParentId()
|
||||
{
|
||||
public Long getParentId() {
|
||||
return parentId;
|
||||
}
|
||||
|
||||
public void setParentId(Long parentId)
|
||||
{
|
||||
public void setParentId(Long parentId) {
|
||||
this.parentId = parentId;
|
||||
}
|
||||
|
||||
@NotNull(message = "显示顺序不能为空")
|
||||
public Integer getOrderNum()
|
||||
{
|
||||
public Integer getOrderNum() {
|
||||
return orderNum;
|
||||
}
|
||||
|
||||
public void setOrderNum(Integer orderNum)
|
||||
{
|
||||
public void setOrderNum(Integer orderNum) {
|
||||
this.orderNum = orderNum;
|
||||
}
|
||||
|
||||
@Size(min = 0, max = 200, message = "路由地址不能超过200个字符")
|
||||
public String getPath()
|
||||
{
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public void setPath(String path)
|
||||
{
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
@Size(min = 0, max = 200, message = "组件路径不能超过255个字符")
|
||||
public String getComponent()
|
||||
{
|
||||
public String getComponent() {
|
||||
return component;
|
||||
}
|
||||
|
||||
public void setComponent(String component)
|
||||
{
|
||||
public void setComponent(String component) {
|
||||
this.component = component;
|
||||
}
|
||||
|
||||
public String getQuery()
|
||||
{
|
||||
public String getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public void setQuery(String query)
|
||||
{
|
||||
public void setQuery(String query) {
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public String getIsFrame()
|
||||
{
|
||||
public String getIsFrame() {
|
||||
return isFrame;
|
||||
}
|
||||
|
||||
public void setIsFrame(String isFrame)
|
||||
{
|
||||
public void setIsFrame(String isFrame) {
|
||||
this.isFrame = isFrame;
|
||||
}
|
||||
|
||||
public String getIsCache()
|
||||
{
|
||||
public String getIsCache() {
|
||||
return isCache;
|
||||
}
|
||||
|
||||
public void setIsCache(String isCache)
|
||||
{
|
||||
public void setIsCache(String isCache) {
|
||||
this.isCache = isCache;
|
||||
}
|
||||
|
||||
@NotBlank(message = "菜单类型不能为空")
|
||||
public String getMenuType()
|
||||
{
|
||||
public String getMenuType() {
|
||||
return menuType;
|
||||
}
|
||||
|
||||
public void setMenuType(String menuType)
|
||||
{
|
||||
public void setMenuType(String menuType) {
|
||||
this.menuType = menuType;
|
||||
}
|
||||
|
||||
public String getVisible()
|
||||
{
|
||||
public String getVisible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
public void setVisible(String visible)
|
||||
{
|
||||
public void setVisible(String visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
|
||||
public String getStatus()
|
||||
{
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status)
|
||||
{
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符")
|
||||
public String getPerms()
|
||||
{
|
||||
public String getPerms() {
|
||||
return perms;
|
||||
}
|
||||
|
||||
public void setPerms(String perms)
|
||||
{
|
||||
public void setPerms(String perms) {
|
||||
this.perms = perms;
|
||||
}
|
||||
|
||||
public String getIcon()
|
||||
{
|
||||
public String getIcon() {
|
||||
return icon;
|
||||
}
|
||||
|
||||
public void setIcon(String icon)
|
||||
{
|
||||
public void setIcon(String icon) {
|
||||
this.icon = icon;
|
||||
}
|
||||
|
||||
public List<SysMenu> getChildren()
|
||||
{
|
||||
public List<SysMenu> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<SysMenu> children)
|
||||
{
|
||||
public void setChildren(List<SysMenu> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("menuId", getMenuId())
|
||||
.append("menuName", getMenuName())
|
||||
.append("parentId", getParentId())
|
||||
.append("orderNum", getOrderNum())
|
||||
.append("path", getPath())
|
||||
.append("component", getComponent())
|
||||
.append("isFrame", getIsFrame())
|
||||
.append("IsCache", getIsCache())
|
||||
.append("menuType", getMenuType())
|
||||
.append("visible", getVisible())
|
||||
.append("status ", getStatus())
|
||||
.append("perms", getPerms())
|
||||
.append("icon", getIcon())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("menuId", getMenuId())
|
||||
.append("menuName", getMenuName())
|
||||
.append("parentId", getParentId())
|
||||
.append("orderNum", getOrderNum())
|
||||
.append("path", getPath())
|
||||
.append("component", getComponent())
|
||||
.append("isFrame", getIsFrame())
|
||||
.append("IsCache", getIsCache())
|
||||
.append("menuType", getMenuType())
|
||||
.append("visible", getVisible())
|
||||
.append("status ", getStatus())
|
||||
.append("perms", getPerms())
|
||||
.append("icon", getIcon())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,102 +1,104 @@
|
|||
package com.ruoyi.system.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
import com.ruoyi.common.core.xss.Xss;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 通知公告表 sys_notice
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SysNotice extends BaseEntity
|
||||
{
|
||||
public class SysNotice extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 公告ID */
|
||||
/**
|
||||
* 公告ID
|
||||
*/
|
||||
private Long noticeId;
|
||||
|
||||
/** 公告标题 */
|
||||
/**
|
||||
* 公告标题
|
||||
*/
|
||||
private String noticeTitle;
|
||||
|
||||
/** 公告类型(1通知 2公告) */
|
||||
/**
|
||||
* 公告类型(1通知 2公告)
|
||||
*/
|
||||
private String noticeType;
|
||||
|
||||
/** 公告内容 */
|
||||
/**
|
||||
* 公告内容
|
||||
*/
|
||||
private String noticeContent;
|
||||
|
||||
/** 公告状态(0正常 1关闭) */
|
||||
/**
|
||||
* 公告状态(0正常 1关闭)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
public Long getNoticeId()
|
||||
{
|
||||
public Long getNoticeId() {
|
||||
return noticeId;
|
||||
}
|
||||
|
||||
public void setNoticeId(Long noticeId)
|
||||
{
|
||||
public void setNoticeId(Long noticeId) {
|
||||
this.noticeId = noticeId;
|
||||
}
|
||||
|
||||
public void setNoticeTitle(String noticeTitle)
|
||||
{
|
||||
public void setNoticeTitle(String noticeTitle) {
|
||||
this.noticeTitle = noticeTitle;
|
||||
}
|
||||
|
||||
@Xss(message = "公告标题不能包含脚本字符")
|
||||
@NotBlank(message = "公告标题不能为空")
|
||||
@Size(min = 0, max = 50, message = "公告标题不能超过50个字符")
|
||||
public String getNoticeTitle()
|
||||
{
|
||||
public String getNoticeTitle() {
|
||||
return noticeTitle;
|
||||
}
|
||||
|
||||
public void setNoticeType(String noticeType)
|
||||
{
|
||||
public void setNoticeType(String noticeType) {
|
||||
this.noticeType = noticeType;
|
||||
}
|
||||
|
||||
public String getNoticeType()
|
||||
{
|
||||
public String getNoticeType() {
|
||||
return noticeType;
|
||||
}
|
||||
|
||||
public void setNoticeContent(String noticeContent)
|
||||
{
|
||||
public void setNoticeContent(String noticeContent) {
|
||||
this.noticeContent = noticeContent;
|
||||
}
|
||||
|
||||
public String getNoticeContent()
|
||||
{
|
||||
public String getNoticeContent() {
|
||||
return noticeContent;
|
||||
}
|
||||
|
||||
public void setStatus(String status)
|
||||
{
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getStatus()
|
||||
{
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("noticeId", getNoticeId())
|
||||
.append("noticeTitle", getNoticeTitle())
|
||||
.append("noticeType", getNoticeType())
|
||||
.append("noticeContent", getNoticeContent())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("noticeId", getNoticeId())
|
||||
.append("noticeTitle", getNoticeTitle())
|
||||
.append("noticeType", getNoticeType())
|
||||
.append("noticeContent", getNoticeContent())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,124 +1,126 @@
|
|||
package com.ruoyi.system.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.core.annotation.Excel;
|
||||
import com.ruoyi.common.core.annotation.Excel.ColumnType;
|
||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 岗位表 sys_post
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SysPost extends BaseEntity
|
||||
{
|
||||
public class SysPost extends BaseEntity {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 岗位序号 */
|
||||
/**
|
||||
* 岗位序号
|
||||
*/
|
||||
@Excel(name = "岗位序号", cellType = ColumnType.NUMERIC)
|
||||
private Long postId;
|
||||
|
||||
/** 岗位编码 */
|
||||
/**
|
||||
* 岗位编码
|
||||
*/
|
||||
@Excel(name = "岗位编码")
|
||||
private String postCode;
|
||||
|
||||
/** 岗位名称 */
|
||||
/**
|
||||
* 岗位名称
|
||||
*/
|
||||
@Excel(name = "岗位名称")
|
||||
private String postName;
|
||||
|
||||
/** 岗位排序 */
|
||||
/**
|
||||
* 岗位排序
|
||||
*/
|
||||
@Excel(name = "岗位排序")
|
||||
private Integer postSort;
|
||||
|
||||
/** 状态(0正常 1停用) */
|
||||
/**
|
||||
* 状态(0正常 1停用)
|
||||
*/
|
||||
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
|
||||
private String status;
|
||||
|
||||
/** 用户是否存在此岗位标识 默认不存在 */
|
||||
/**
|
||||
* 用户是否存在此岗位标识 默认不存在
|
||||
*/
|
||||
private boolean flag = false;
|
||||
|
||||
public Long getPostId()
|
||||
{
|
||||
public Long getPostId() {
|
||||
return postId;
|
||||
}
|
||||
|
||||
public void setPostId(Long postId)
|
||||
{
|
||||
public void setPostId(Long postId) {
|
||||
this.postId = postId;
|
||||
}
|
||||
|
||||
@NotBlank(message = "岗位编码不能为空")
|
||||
@Size(min = 0, max = 64, message = "岗位编码长度不能超过64个字符")
|
||||
public String getPostCode()
|
||||
{
|
||||
public String getPostCode() {
|
||||
return postCode;
|
||||
}
|
||||
|
||||
public void setPostCode(String postCode)
|
||||
{
|
||||
public void setPostCode(String postCode) {
|
||||
this.postCode = postCode;
|
||||
}
|
||||
|
||||
@NotBlank(message = "岗位名称不能为空")
|
||||
@Size(min = 0, max = 50, message = "岗位名称长度不能超过50个字符")
|
||||
public String getPostName()
|
||||
{
|
||||
public String getPostName() {
|
||||
return postName;
|
||||
}
|
||||
|
||||
public void setPostName(String postName)
|
||||
{
|
||||
public void setPostName(String postName) {
|
||||
this.postName = postName;
|
||||
}
|
||||
|
||||
@NotNull(message = "显示顺序不能为空")
|
||||
public Integer getPostSort()
|
||||
{
|
||||
public Integer getPostSort() {
|
||||
return postSort;
|
||||
}
|
||||
|
||||
public void setPostSort(Integer postSort)
|
||||
{
|
||||
public void setPostSort(Integer postSort) {
|
||||
this.postSort = postSort;
|
||||
}
|
||||
|
||||
public String getStatus()
|
||||
{
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status)
|
||||
{
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isFlag()
|
||||
{
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setFlag(boolean flag)
|
||||
{
|
||||
public void setFlag(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("postId", getPostId())
|
||||
.append("postCode", getPostCode())
|
||||
.append("postName", getPostName())
|
||||
.append("postSort", getPostSort())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("postId", getPostId())
|
||||
.append("postCode", getPostCode())
|
||||
.append("postName", getPostName())
|
||||
.append("postSort", getPostSort())
|
||||
.append("status", getStatus())
|
||||
.append("createBy", getCreateBy())
|
||||
.append("createTime", getCreateTime())
|
||||
.append("updateBy", getUpdateBy())
|
||||
.append("updateTime", getUpdateTime())
|
||||
.append("remark", getRemark())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@ package com.ruoyi.system.service.impl;
|
|||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.ruoyi.common.core.constant.CacheConstants;
|
||||
|
|
@ -17,12 +18,11 @@ import com.ruoyi.system.service.ISysConfigService;
|
|||
|
||||
/**
|
||||
* 参数配置 服务层实现
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class SysConfigServiceImpl implements ISysConfigService
|
||||
{
|
||||
public class SysConfigServiceImpl implements ISysConfigService {
|
||||
@Autowired
|
||||
private SysConfigMapper configMapper;
|
||||
|
||||
|
|
@ -33,20 +33,18 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
* 项目启动时,初始化参数到缓存
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init()
|
||||
{
|
||||
public void init() {
|
||||
loadingConfigCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询参数配置信息
|
||||
*
|
||||
*
|
||||
* @param configId 参数配置ID
|
||||
* @return 参数配置信息
|
||||
*/
|
||||
@Override
|
||||
public SysConfig selectConfigById(Long configId)
|
||||
{
|
||||
public SysConfig selectConfigById(Long configId) {
|
||||
SysConfig config = new SysConfig();
|
||||
config.setConfigId(configId);
|
||||
return configMapper.selectConfig(config);
|
||||
|
|
@ -54,23 +52,20 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
|
||||
/**
|
||||
* 根据键名查询参数配置信息
|
||||
*
|
||||
*
|
||||
* @param configKey 参数key
|
||||
* @return 参数键值
|
||||
*/
|
||||
@Override
|
||||
public String selectConfigByKey(String configKey)
|
||||
{
|
||||
public String selectConfigByKey(String configKey) {
|
||||
String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
|
||||
if (StringUtils.isNotEmpty(configValue))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(configValue)) {
|
||||
return configValue;
|
||||
}
|
||||
SysConfig config = new SysConfig();
|
||||
config.setConfigKey(configKey);
|
||||
SysConfig retConfig = configMapper.selectConfig(config);
|
||||
if (StringUtils.isNotNull(retConfig))
|
||||
{
|
||||
if (StringUtils.isNotNull(retConfig)) {
|
||||
redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
|
||||
return retConfig.getConfigValue();
|
||||
}
|
||||
|
|
@ -79,28 +74,25 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
|
||||
/**
|
||||
* 查询参数配置列表
|
||||
*
|
||||
*
|
||||
* @param config 参数配置信息
|
||||
* @return 参数配置集合
|
||||
*/
|
||||
@Override
|
||||
public List<SysConfig> selectConfigList(SysConfig config)
|
||||
{
|
||||
public List<SysConfig> selectConfigList(SysConfig config) {
|
||||
return configMapper.selectConfigList(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增参数配置
|
||||
*
|
||||
*
|
||||
* @param config 参数配置信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int insertConfig(SysConfig config)
|
||||
{
|
||||
public int insertConfig(SysConfig config) {
|
||||
int row = configMapper.insertConfig(config);
|
||||
if (row > 0)
|
||||
{
|
||||
if (row > 0) {
|
||||
redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
|
||||
}
|
||||
return row;
|
||||
|
|
@ -108,22 +100,19 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
|
||||
/**
|
||||
* 修改参数配置
|
||||
*
|
||||
*
|
||||
* @param config 参数配置信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int updateConfig(SysConfig config)
|
||||
{
|
||||
public int updateConfig(SysConfig config) {
|
||||
SysConfig temp = configMapper.selectConfigById(config.getConfigId());
|
||||
if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey()))
|
||||
{
|
||||
if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
|
||||
redisService.deleteObject(getCacheKey(temp.getConfigKey()));
|
||||
}
|
||||
|
||||
int row = configMapper.updateConfig(config);
|
||||
if (row > 0)
|
||||
{
|
||||
if (row > 0) {
|
||||
redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
|
||||
}
|
||||
return row;
|
||||
|
|
@ -131,17 +120,14 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
|
||||
/**
|
||||
* 批量删除参数信息
|
||||
*
|
||||
*
|
||||
* @param configIds 需要删除的参数ID
|
||||
*/
|
||||
@Override
|
||||
public void deleteConfigByIds(Long[] configIds)
|
||||
{
|
||||
for (Long configId : configIds)
|
||||
{
|
||||
public void deleteConfigByIds(Long[] configIds) {
|
||||
for (Long configId : configIds) {
|
||||
SysConfig config = selectConfigById(configId);
|
||||
if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
|
||||
{
|
||||
if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
|
||||
throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
|
||||
}
|
||||
configMapper.deleteConfigById(configId);
|
||||
|
|
@ -153,11 +139,9 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
* 加载参数缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void loadingConfigCache()
|
||||
{
|
||||
public void loadingConfigCache() {
|
||||
List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
|
||||
for (SysConfig config : configsList)
|
||||
{
|
||||
for (SysConfig config : configsList) {
|
||||
redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
|
||||
}
|
||||
}
|
||||
|
|
@ -166,8 +150,7 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
* 清空参数缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void clearConfigCache()
|
||||
{
|
||||
public void clearConfigCache() {
|
||||
Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
|
||||
redisService.deleteObject(keys);
|
||||
}
|
||||
|
|
@ -176,25 +159,22 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
* 重置参数缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void resetConfigCache()
|
||||
{
|
||||
public void resetConfigCache() {
|
||||
clearConfigCache();
|
||||
loadingConfigCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验参数键名是否唯一
|
||||
*
|
||||
*
|
||||
* @param config 参数配置信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean checkConfigKeyUnique(SysConfig config)
|
||||
{
|
||||
public boolean checkConfigKeyUnique(SysConfig config) {
|
||||
Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
|
||||
SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());
|
||||
if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue())
|
||||
{
|
||||
if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
|
||||
return UserConstants.NOT_UNIQUE;
|
||||
}
|
||||
return UserConstants.UNIQUE;
|
||||
|
|
@ -202,12 +182,11 @@ public class SysConfigServiceImpl implements ISysConfigService
|
|||
|
||||
/**
|
||||
* 设置cache key
|
||||
*
|
||||
*
|
||||
* @param configKey 参数键
|
||||
* @return 缓存键key
|
||||
*/
|
||||
private String getCacheKey(String configKey)
|
||||
{
|
||||
private String getCacheKey(String configKey) {
|
||||
return CacheConstants.SYS_CONFIG_KEY + configKey;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import java.util.Comparator;
|
|||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
|
@ -20,12 +21,11 @@ import com.ruoyi.system.service.ISysDictTypeService;
|
|||
|
||||
/**
|
||||
* 字典 业务层处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class SysDictTypeServiceImpl implements ISysDictTypeService
|
||||
{
|
||||
public class SysDictTypeServiceImpl implements ISysDictTypeService {
|
||||
@Autowired
|
||||
private SysDictTypeMapper dictTypeMapper;
|
||||
|
||||
|
|
@ -36,51 +36,45 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
* 项目启动时,初始化字典到缓存
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init()
|
||||
{
|
||||
public void init() {
|
||||
loadingDictCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件分页查询字典类型
|
||||
*
|
||||
*
|
||||
* @param dictType 字典类型信息
|
||||
* @return 字典类型集合信息
|
||||
*/
|
||||
@Override
|
||||
public List<SysDictType> selectDictTypeList(SysDictType dictType)
|
||||
{
|
||||
public List<SysDictType> selectDictTypeList(SysDictType dictType) {
|
||||
return dictTypeMapper.selectDictTypeList(dictType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据所有字典类型
|
||||
*
|
||||
*
|
||||
* @return 字典类型集合信息
|
||||
*/
|
||||
@Override
|
||||
public List<SysDictType> selectDictTypeAll()
|
||||
{
|
||||
public List<SysDictType> selectDictTypeAll() {
|
||||
return dictTypeMapper.selectDictTypeAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据字典类型查询字典数据
|
||||
*
|
||||
*
|
||||
* @param dictType 字典类型
|
||||
* @return 字典数据集合信息
|
||||
*/
|
||||
@Override
|
||||
public List<SysDictData> selectDictDataByType(String dictType)
|
||||
{
|
||||
public List<SysDictData> selectDictDataByType(String dictType) {
|
||||
List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
|
||||
if (StringUtils.isNotEmpty(dictDatas))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(dictDatas)) {
|
||||
return dictDatas;
|
||||
}
|
||||
dictDatas = dictDataMapper.selectDictDataByType(dictType);
|
||||
if (StringUtils.isNotEmpty(dictDatas))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(dictDatas)) {
|
||||
DictUtils.setDictCache(dictType, dictDatas);
|
||||
return dictDatas;
|
||||
}
|
||||
|
|
@ -89,41 +83,36 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
|
||||
/**
|
||||
* 根据字典类型ID查询信息
|
||||
*
|
||||
*
|
||||
* @param dictId 字典类型ID
|
||||
* @return 字典类型
|
||||
*/
|
||||
@Override
|
||||
public SysDictType selectDictTypeById(Long dictId)
|
||||
{
|
||||
public SysDictType selectDictTypeById(Long dictId) {
|
||||
return dictTypeMapper.selectDictTypeById(dictId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据字典类型查询信息
|
||||
*
|
||||
*
|
||||
* @param dictType 字典类型
|
||||
* @return 字典类型
|
||||
*/
|
||||
@Override
|
||||
public SysDictType selectDictTypeByType(String dictType)
|
||||
{
|
||||
public SysDictType selectDictTypeByType(String dictType) {
|
||||
return dictTypeMapper.selectDictTypeByType(dictType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除字典类型信息
|
||||
*
|
||||
*
|
||||
* @param dictIds 需要删除的字典ID
|
||||
*/
|
||||
@Override
|
||||
public void deleteDictTypeByIds(Long[] dictIds)
|
||||
{
|
||||
for (Long dictId : dictIds)
|
||||
{
|
||||
public void deleteDictTypeByIds(Long[] dictIds) {
|
||||
for (Long dictId : dictIds) {
|
||||
SysDictType dictType = selectDictTypeById(dictId);
|
||||
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0)
|
||||
{
|
||||
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
|
||||
throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
|
||||
}
|
||||
dictTypeMapper.deleteDictTypeById(dictId);
|
||||
|
|
@ -135,13 +124,11 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
* 加载字典缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void loadingDictCache()
|
||||
{
|
||||
public void loadingDictCache() {
|
||||
SysDictData dictData = new SysDictData();
|
||||
dictData.setStatus("0");
|
||||
Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
|
||||
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet())
|
||||
{
|
||||
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
|
||||
DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
|
|
@ -150,8 +137,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
* 清空字典缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void clearDictCache()
|
||||
{
|
||||
public void clearDictCache() {
|
||||
DictUtils.clearDictCache();
|
||||
}
|
||||
|
||||
|
|
@ -159,24 +145,21 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
* 重置字典缓存数据
|
||||
*/
|
||||
@Override
|
||||
public void resetDictCache()
|
||||
{
|
||||
public void resetDictCache() {
|
||||
clearDictCache();
|
||||
loadingDictCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增保存字典类型信息
|
||||
*
|
||||
*
|
||||
* @param dict 字典类型信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int insertDictType(SysDictType dict)
|
||||
{
|
||||
public int insertDictType(SysDictType dict) {
|
||||
int row = dictTypeMapper.insertDictType(dict);
|
||||
if (row > 0)
|
||||
{
|
||||
if (row > 0) {
|
||||
DictUtils.setDictCache(dict.getDictType(), null);
|
||||
}
|
||||
return row;
|
||||
|
|
@ -184,19 +167,17 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
|
||||
/**
|
||||
* 修改保存字典类型信息
|
||||
*
|
||||
*
|
||||
* @param dict 字典类型信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateDictType(SysDictType dict)
|
||||
{
|
||||
public int updateDictType(SysDictType dict) {
|
||||
SysDictType oldDict = dictTypeMapper.selectDictTypeById(dict.getDictId());
|
||||
dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
|
||||
int row = dictTypeMapper.updateDictType(dict);
|
||||
if (row > 0)
|
||||
{
|
||||
if (row > 0) {
|
||||
List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
|
||||
DictUtils.setDictCache(dict.getDictType(), dictDatas);
|
||||
}
|
||||
|
|
@ -205,17 +186,15 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
|
|||
|
||||
/**
|
||||
* 校验字典类型称是否唯一
|
||||
*
|
||||
*
|
||||
* @param dict 字典类型
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean checkDictTypeUnique(SysDictType dict)
|
||||
{
|
||||
Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
|
||||
public boolean checkDictTypeUnique(SysDictType dict) {
|
||||
long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
|
||||
SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
|
||||
if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue())
|
||||
{
|
||||
if (StringUtils.isNotNull(dictType) && dictType.getDictId() != dictId) {
|
||||
return UserConstants.NOT_UNIQUE;
|
||||
}
|
||||
return UserConstants.UNIQUE;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ package com.ruoyi.system.service.impl;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.Validator;
|
||||
|
||||
import jakarta.validation.Validator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
|
@ -32,12 +33,11 @@ import com.ruoyi.system.service.ISysUserService;
|
|||
|
||||
/**
|
||||
* 用户 业务层处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Service
|
||||
public class SysUserServiceImpl implements ISysUserService
|
||||
{
|
||||
public class SysUserServiceImpl implements ISysUserService {
|
||||
private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
|
||||
|
||||
@Autowired
|
||||
|
|
@ -63,79 +63,72 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 根据条件分页查询用户列表
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 用户信息集合信息
|
||||
*/
|
||||
@Override
|
||||
@DataScope(deptAlias = "d", userAlias = "u")
|
||||
public List<SysUser> selectUserList(SysUser user)
|
||||
{
|
||||
public List<SysUser> selectUserList(SysUser user) {
|
||||
return userMapper.selectUserList(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件分页查询已分配用户角色列表
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 用户信息集合信息
|
||||
*/
|
||||
@Override
|
||||
@DataScope(deptAlias = "d", userAlias = "u")
|
||||
public List<SysUser> selectAllocatedList(SysUser user)
|
||||
{
|
||||
public List<SysUser> selectAllocatedList(SysUser user) {
|
||||
return userMapper.selectAllocatedList(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件分页查询未分配用户角色列表
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 用户信息集合信息
|
||||
*/
|
||||
@Override
|
||||
@DataScope(deptAlias = "d", userAlias = "u")
|
||||
public List<SysUser> selectUnallocatedList(SysUser user)
|
||||
{
|
||||
public List<SysUser> selectUnallocatedList(SysUser user) {
|
||||
return userMapper.selectUnallocatedList(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过用户名查询用户
|
||||
*
|
||||
*
|
||||
* @param userName 用户名
|
||||
* @return 用户对象信息
|
||||
*/
|
||||
@Override
|
||||
public SysUser selectUserByUserName(String userName)
|
||||
{
|
||||
public SysUser selectUserByUserName(String userName) {
|
||||
return userMapper.selectUserByUserName(userName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过用户ID查询用户
|
||||
*
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 用户对象信息
|
||||
*/
|
||||
@Override
|
||||
public SysUser selectUserById(Long userId)
|
||||
{
|
||||
public SysUser selectUserById(Long userId) {
|
||||
return userMapper.selectUserById(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询用户所属角色组
|
||||
*
|
||||
*
|
||||
* @param userName 用户名
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public String selectUserRoleGroup(String userName)
|
||||
{
|
||||
public String selectUserRoleGroup(String userName) {
|
||||
List<SysRole> list = roleMapper.selectRolesByUserName(userName);
|
||||
if (CollectionUtils.isEmpty(list))
|
||||
{
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
|
||||
|
|
@ -143,16 +136,14 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 查询用户所属岗位组
|
||||
*
|
||||
*
|
||||
* @param userName 用户名
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public String selectUserPostGroup(String userName)
|
||||
{
|
||||
public String selectUserPostGroup(String userName) {
|
||||
List<SysPost> list = postMapper.selectPostsByUserName(userName);
|
||||
if (CollectionUtils.isEmpty(list))
|
||||
{
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
|
||||
|
|
@ -160,17 +151,15 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 校验用户名称是否唯一
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean checkUserNameUnique(SysUser user)
|
||||
{
|
||||
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
public boolean checkUserNameUnique(SysUser user) {
|
||||
long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
SysUser info = userMapper.checkUserNameUnique(user.getUserName());
|
||||
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
|
||||
{
|
||||
if (StringUtils.isNotNull(info) && info.getUserId() != userId) {
|
||||
return UserConstants.NOT_UNIQUE;
|
||||
}
|
||||
return UserConstants.UNIQUE;
|
||||
|
|
@ -180,15 +169,12 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
* 校验手机号码是否唯一
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean checkPhoneUnique(SysUser user)
|
||||
{
|
||||
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
public boolean checkPhoneUnique(SysUser user) {
|
||||
long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
|
||||
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
|
||||
{
|
||||
if (StringUtils.isNotNull(info) && info.getUserId() != userId) {
|
||||
return UserConstants.NOT_UNIQUE;
|
||||
}
|
||||
return UserConstants.UNIQUE;
|
||||
|
|
@ -198,15 +184,12 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
* 校验email是否唯一
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean checkEmailUnique(SysUser user)
|
||||
{
|
||||
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
public boolean checkEmailUnique(SysUser user) {
|
||||
long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
|
||||
SysUser info = userMapper.checkEmailUnique(user.getEmail());
|
||||
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
|
||||
{
|
||||
if (StringUtils.isNotNull(info) && info.getUserId() != userId) {
|
||||
return UserConstants.NOT_UNIQUE;
|
||||
}
|
||||
return UserConstants.UNIQUE;
|
||||
|
|
@ -214,33 +197,28 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 校验用户是否允许操作
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
*/
|
||||
@Override
|
||||
public void checkUserAllowed(SysUser user)
|
||||
{
|
||||
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
|
||||
{
|
||||
public void checkUserAllowed(SysUser user) {
|
||||
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
|
||||
throw new ServiceException("不允许操作超级管理员用户");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验用户是否有数据权限
|
||||
*
|
||||
*
|
||||
* @param userId 用户id
|
||||
*/
|
||||
@Override
|
||||
public void checkUserDataScope(Long userId)
|
||||
{
|
||||
if (!SysUser.isAdmin(SecurityUtils.getUserId()))
|
||||
{
|
||||
public void checkUserDataScope(Long userId) {
|
||||
if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
|
||||
SysUser user = new SysUser();
|
||||
user.setUserId(userId);
|
||||
List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
|
||||
if (StringUtils.isEmpty(users))
|
||||
{
|
||||
if (StringUtils.isEmpty(users)) {
|
||||
throw new ServiceException("没有权限访问用户数据!");
|
||||
}
|
||||
}
|
||||
|
|
@ -248,14 +226,13 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 新增保存用户信息
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int insertUser(SysUser user)
|
||||
{
|
||||
public int insertUser(SysUser user) {
|
||||
// 新增用户信息
|
||||
int rows = userMapper.insertUser(user);
|
||||
// 新增用户岗位关联
|
||||
|
|
@ -267,26 +244,24 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 注册用户信息
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean registerUser(SysUser user)
|
||||
{
|
||||
public boolean registerUser(SysUser user) {
|
||||
return userMapper.insertUser(user) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改保存用户信息
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateUser(SysUser user)
|
||||
{
|
||||
public int updateUser(SysUser user) {
|
||||
Long userId = user.getUserId();
|
||||
// 删除用户与角色关联
|
||||
userRoleMapper.deleteUserRoleByUserId(userId);
|
||||
|
|
@ -301,104 +276,94 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 用户授权角色
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param roleIds 角色组
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void insertUserAuth(Long userId, Long[] roleIds)
|
||||
{
|
||||
public void insertUserAuth(Long userId, Long[] roleIds) {
|
||||
userRoleMapper.deleteUserRoleByUserId(userId);
|
||||
insertUserRole(userId, roleIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户状态
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int updateUserStatus(SysUser user)
|
||||
{
|
||||
public int updateUserStatus(SysUser user) {
|
||||
return userMapper.updateUser(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户基本信息
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int updateUserProfile(SysUser user)
|
||||
{
|
||||
public int updateUserProfile(SysUser user) {
|
||||
return userMapper.updateUser(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户头像
|
||||
*
|
||||
*
|
||||
* @param userName 用户名
|
||||
* @param avatar 头像地址
|
||||
* @param avatar 头像地址
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public boolean updateUserAvatar(String userName, String avatar)
|
||||
{
|
||||
public boolean updateUserAvatar(String userName, String avatar) {
|
||||
return userMapper.updateUserAvatar(userName, avatar) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置用户密码
|
||||
*
|
||||
*
|
||||
* @param user 用户信息
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int resetPwd(SysUser user)
|
||||
{
|
||||
public int resetPwd(SysUser user) {
|
||||
return userMapper.updateUser(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置用户密码
|
||||
*
|
||||
*
|
||||
* @param userName 用户名
|
||||
* @param password 密码
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int resetUserPwd(String userName, String password)
|
||||
{
|
||||
public int resetUserPwd(String userName, String password) {
|
||||
return userMapper.resetUserPwd(userName, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增用户角色信息
|
||||
*
|
||||
*
|
||||
* @param user 用户对象
|
||||
*/
|
||||
public void insertUserRole(SysUser user)
|
||||
{
|
||||
public void insertUserRole(SysUser user) {
|
||||
this.insertUserRole(user.getUserId(), user.getRoleIds());
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增用户岗位信息
|
||||
*
|
||||
*
|
||||
* @param user 用户对象
|
||||
*/
|
||||
public void insertUserPost(SysUser user)
|
||||
{
|
||||
public void insertUserPost(SysUser user) {
|
||||
Long[] posts = user.getPostIds();
|
||||
if (StringUtils.isNotEmpty(posts))
|
||||
{
|
||||
if (StringUtils.isNotEmpty(posts)) {
|
||||
// 新增用户与岗位管理
|
||||
List<SysUserPost> list = new ArrayList<SysUserPost>();
|
||||
for (Long postId : posts)
|
||||
{
|
||||
for (Long postId : posts) {
|
||||
SysUserPost up = new SysUserPost();
|
||||
up.setUserId(user.getUserId());
|
||||
up.setPostId(postId);
|
||||
|
|
@ -410,18 +375,15 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 新增用户角色信息
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param roleIds 角色组
|
||||
*/
|
||||
public void insertUserRole(Long userId, Long[] roleIds)
|
||||
{
|
||||
if (StringUtils.isNotEmpty(roleIds))
|
||||
{
|
||||
public void insertUserRole(Long userId, Long[] roleIds) {
|
||||
if (StringUtils.isNotEmpty(roleIds)) {
|
||||
// 新增用户与角色管理
|
||||
List<SysUserRole> list = new ArrayList<SysUserRole>();
|
||||
for (Long roleId : roleIds)
|
||||
{
|
||||
for (Long roleId : roleIds) {
|
||||
SysUserRole ur = new SysUserRole();
|
||||
ur.setUserId(userId);
|
||||
ur.setRoleId(roleId);
|
||||
|
|
@ -433,14 +395,13 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 通过用户ID删除用户
|
||||
*
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int deleteUserById(Long userId)
|
||||
{
|
||||
public int deleteUserById(Long userId) {
|
||||
// 删除用户与角色关联
|
||||
userRoleMapper.deleteUserRoleByUserId(userId);
|
||||
// 删除用户与岗位表
|
||||
|
|
@ -450,16 +411,14 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 批量删除用户信息
|
||||
*
|
||||
*
|
||||
* @param userIds 需要删除的用户ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int deleteUserByIds(Long[] userIds)
|
||||
{
|
||||
for (Long userId : userIds)
|
||||
{
|
||||
public int deleteUserByIds(Long[] userIds) {
|
||||
for (Long userId : userIds) {
|
||||
checkUserAllowed(new SysUser(userId));
|
||||
checkUserDataScope(userId);
|
||||
}
|
||||
|
|
@ -472,17 +431,15 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
|
||||
/**
|
||||
* 导入用户数据
|
||||
*
|
||||
* @param userList 用户数据列表
|
||||
*
|
||||
* @param userList 用户数据列表
|
||||
* @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据
|
||||
* @param operName 操作用户
|
||||
* @param operName 操作用户
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
|
||||
{
|
||||
if (StringUtils.isNull(userList) || userList.size() == 0)
|
||||
{
|
||||
public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
|
||||
if (StringUtils.isNull(userList) || userList.isEmpty()) {
|
||||
throw new ServiceException("导入用户数据不能为空!");
|
||||
}
|
||||
int successNum = 0;
|
||||
|
|
@ -490,23 +447,18 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
StringBuilder successMsg = new StringBuilder();
|
||||
StringBuilder failureMsg = new StringBuilder();
|
||||
String password = configService.selectConfigByKey("sys.user.initPassword");
|
||||
for (SysUser user : userList)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (SysUser user : userList) {
|
||||
try {
|
||||
// 验证是否存在这个用户
|
||||
SysUser u = userMapper.selectUserByUserName(user.getUserName());
|
||||
if (StringUtils.isNull(u))
|
||||
{
|
||||
if (StringUtils.isNull(u)) {
|
||||
BeanValidators.validateWithException(validator, user);
|
||||
user.setPassword(SecurityUtils.encryptPassword(password));
|
||||
user.setCreateBy(operName);
|
||||
userMapper.insertUser(user);
|
||||
successNum++;
|
||||
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
|
||||
}
|
||||
else if (isUpdateSupport)
|
||||
{
|
||||
successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
|
||||
} else if (isUpdateSupport) {
|
||||
BeanValidators.validateWithException(validator, user);
|
||||
checkUserAllowed(u);
|
||||
checkUserDataScope(u.getUserId());
|
||||
|
|
@ -514,29 +466,22 @@ public class SysUserServiceImpl implements ISysUserService
|
|||
user.setUpdateBy(operName);
|
||||
userMapper.updateUser(user);
|
||||
successNum++;
|
||||
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
|
||||
}
|
||||
else
|
||||
{
|
||||
successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
|
||||
} else {
|
||||
failureNum++;
|
||||
failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
|
||||
failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
failureNum++;
|
||||
String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败:";
|
||||
failureMsg.append(msg + e.getMessage());
|
||||
failureMsg.append(msg).append(e.getMessage());
|
||||
log.error(msg, e);
|
||||
}
|
||||
}
|
||||
if (failureNum > 0)
|
||||
{
|
||||
if (failureNum > 0) {
|
||||
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
|
||||
throw new ServiceException(failureMsg.toString());
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
|
||||
}
|
||||
return successMsg.toString();
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# 页面标题
|
||||
VITE_APP_TITLE = 若依管理系统DEV
|
||||
VITE_APP_TITLE=RYAS管理系统
|
||||
|
||||
# 开发环境配置
|
||||
VITE_APP_ENV = 'development'
|
||||
VITE_APP_ENV='development'
|
||||
|
||||
# 若依管理系统/开发环境
|
||||
VITE_APP_BASE_API = '/dev-api'
|
||||
VITE_APP_BASE_API='/dev-api'
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
# 页面标题
|
||||
VITE_APP_TITLE = 若依管理系统PROD
|
||||
VITE_APP_TITLE=RYAS管理系统
|
||||
|
||||
# 生产环境配置
|
||||
VITE_APP_ENV = 'production'
|
||||
VITE_APP_ENV='production'
|
||||
|
||||
# 若依管理系统/生产环境
|
||||
VITE_APP_BASE_API = '/prod-api'
|
||||
VITE_APP_BASE_API='/prod-api'
|
||||
|
||||
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
||||
VITE_BUILD_COMPRESS = gzip
|
||||
VITE_BUILD_COMPRESS=gzip
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
# 页面标题
|
||||
VITE_APP_TITLE = 若依管理系统STAGING
|
||||
VITE_APP_TITLE=RYAS管理系统
|
||||
|
||||
# 生产环境配置
|
||||
VITE_APP_ENV = 'staging'
|
||||
VITE_APP_ENV='staging'
|
||||
|
||||
# 若依管理系统/生产环境
|
||||
VITE_APP_BASE_API = '/stage-api'
|
||||
VITE_APP_BASE_API='/stage-api'
|
||||
|
||||
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
||||
VITE_BUILD_COMPRESS = gzip
|
||||
VITE_BUILD_COMPRESS=gzip
|
||||
|
|
@ -7,7 +7,7 @@
|
|||
<meta name="renderer" content="webkit">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<title>若依管理系统</title>
|
||||
<title>RYAS管理系统</title>
|
||||
<!--[if lt IE 11]><script>window.location.href='/html/ie.html';</script><![endif]-->
|
||||
<style>
|
||||
html,
|
||||
|
|
@ -206,7 +206,7 @@
|
|||
<div id="loader"></div>
|
||||
<div class="loader-section section-left"></div>
|
||||
<div class="loader-section section-right"></div>
|
||||
<div class="load_title">正在加载系统资源,请耐心等待</div>
|
||||
<div class="load_title">正在加载系统资源,请稍等... ...</div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue