JeecgBoot 2.1.1 代码生成器AI版本发布

This commit is contained in:
zhangdaihao
2019-10-18 18:37:41 +08:00
parent 9e8b97a0d9
commit 04c0ea55f2
267 changed files with 16761 additions and 26860 deletions

View File

@ -1,24 +0,0 @@
【第一部分】代码注释规范
[1].代码修改注释
//update-begin--Author:zhangdaihao Date:20140212 for[bugfree号]树机构调整--------------------
//update-end--Author:zhangdaihao Date:20140212 for[bugfree号]树机构调整----------------------
[2].代码存在缺陷或者留有功能点的代码,采用以下方式进行标示
//TODO authorzhangdaihao for:插入未完成 date:20130711
[3].SVN提交注释
[author:用户名 date:20130203 for(bugfree号码)增加查询条件,组织机构]
【第二部分】修改文件记录
代码修改日志 /jeecg-boot/docs/代码修改日志
数据库修改日志:/jeecg-boot/docs/DB修改日志.sql
【第三部分】建表规范
1.主键必须是ID,字符串类型32位长度唯一索引;
2.建表标准字段,必须有:创建人、创建时间、修改人、修改时间等标准字段;
3.表字段注释,每个字段必须设置注释说明;
4.表字段注释状态类型的字段必须说明取值规则比如性别sex取值规则
比如:'性别 0/男,1/女'
5.索引,查询频率高的字段加索引(单字段索引 、组合索引);
6.类型字段尽量用字符串varchar类型1-2长度少用int类型避免不必要的问题。

View File

@ -1,18 +0,0 @@
一、技术文档
http://jeecg-boot.mydoc.io
二、部署文档
修改redis、数据库配置文件
修改上传文件目录
修改登录页面提示账号密码
修改前端API的图片访问域名
重要方法:
动态加载路由的类: SysPermissionController.queryByUser
路由name命名规则 通过菜单URL生成路由name去掉URL前缀斜杠替换内容中的斜杠/’为-
举例: URL = /isystem/role
RouteName = isystem-role

View File

@ -3,12 +3,12 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jeecg-boot-module-system</artifactId>
<version>2.1.0</version>
<version>2.1.1</version>
<parent>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-parent</artifactId>
<version>2.1.0</version>
<version>2.1.1</version>
</parent>
<repositories>
@ -35,24 +35,6 @@
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-base-common</artifactId>
</dependency>
<!-- online form-->
<dependency>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>online-form</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- online form -->
</dependencies>
<build>

View File

@ -2,6 +2,7 @@ package org.jeecg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
@ -13,22 +14,22 @@ import java.net.UnknownHostException;
@Slf4j
@EnableSwagger2
@SpringBootApplication
@EnableAutoConfiguration
public class JeecgApplication {
public static void main(String[] args) throws UnknownHostException {
//System.setProperty("spring.devtools.restart.enabled", "true");
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(JeecgApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
log.info("\n----------------------------------------------------------\n\t" +
"Application Jeecg-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" +
"swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
"Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
ConfigurableApplicationContext application = SpringApplication.run(JeecgApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
log.info("\n----------------------------------------------------------\n\t" +
"Application Jeecg-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" +
"swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
"Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
}
}

View File

@ -10,7 +10,7 @@ import org.jeecgframework.codegenerate.window.CodeWindow;
*/
public class JeecgOneGUI {
/** 详细使用手册: http://jeecg-boot.mydoc.io/?t=338140 */
/** 详细使用手册: http://doc.jeecg.com/1275846 */
public static void main(String[] args) {
new CodeWindow().pack();
}

View File

@ -20,6 +20,7 @@ public class MybatisPlusConfig {
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
// 设置sql的limit为无限制默认是500
return new PaginationInterceptor().setLimit(-1);
}

View File

@ -6,6 +6,7 @@ import java.util.Arrays;
import javax.annotation.Resource;
import org.jeecg.common.constant.CacheConstant;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
@ -36,28 +37,31 @@ public class RedisConfig extends CachingConfigurerSupport {
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
/**
* @description 自定义的缓存key的生成策略 若想使用这个key
* 只需要讲注解上keyGenerator的值设置为keyGenerator即可</br>
* @return 自定义策略生成的key
*/
@Override
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getDeclaringClass().getName());
Arrays.stream(params).map(Object::toString).forEach(sb::append);
return sb.toString();
}
};
}
// /**
// * @description 自定义的缓存key的生成策略 若想使用这个key
// * 只需要讲注解上keyGenerator的值设置为keyGenerator即可</br>
// * @return 自定义策略生成的key
// */
// @Override
// @Bean
// public KeyGenerator keyGenerator() {
// return new KeyGenerator() {
// @Override
// public Object generate(Object target, Method method, Object... params) {
// StringBuilder sb = new StringBuilder();
// sb.append(target.getClass().getName());
// sb.append(method.getDeclaringClass().getName());
// Arrays.stream(params).map(Object::toString).forEach(sb::append);
// return sb.toString();
// }
// };
// }
/**
* RedisTemplate配置
*
* @param lettuceConnectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
@ -81,11 +85,14 @@ public class RedisConfig extends CachingConfigurerSupport {
/**
* 缓存配置管理器
*
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(LettuceConnectionFactory factory) {
// 配置序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
// 配置序列化(缓存默认有效期 6小时
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(6));
RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
@ -94,9 +101,9 @@ public class RedisConfig extends CachingConfigurerSupport {
// 创建默认缓存配置对象
/* 默认配置,设置缓存有效期 1小时*/
//RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
/* 配置test的超时时间为120s*/
/* 自定义配置test:demo 的超时时间为 5分钟*/
RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter(factory)).cacheDefaults(redisCacheConfiguration)
.withInitialCacheConfigurations(singletonMap("test", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(120)).disableCachingNullValues()))
.withInitialCacheConfigurations(singletonMap(CacheConstant.TEST_DEMO_CACHE, RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)).disableCachingNullValues()))
.transactionAware().build();
return cacheManager;
}

View File

@ -1,11 +1,6 @@
package org.jeecg.config;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.Filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
@ -13,12 +8,22 @@ import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.shiro.authc.ShiroRealm;
import org.jeecg.modules.shiro.authc.aop.JwtFilter;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.util.StringUtils;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author: Scott
@ -26,9 +31,22 @@ import org.springframework.context.annotation.DependsOn;
* @description: shiro 配置类
*/
@Slf4j
@Configuration
public class ShiroConfig {
@Value("${jeecg.shiro.excludeUrls}")
private String excludeUrls;
@Value("${spring.redis.port}")
private String port;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String redisPassword;
/**
* Filter Chain定义说明
*
@ -42,10 +60,18 @@ public class ShiroConfig {
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 拦截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
if(oConvertUtils.isNotEmpty(excludeUrls)){
String[] permissionUrl = excludeUrls.split(",");
for(String url : permissionUrl){
filterChainDefinitionMap.put(url,"anon");
}
}
//cas验证登录
filterChainDefinitionMap.put("/cas/client/validateLogin", "anon");
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/sys/getCheckCode", "anon"); //登录验证码接口排除
filterChainDefinitionMap.put("/sys/login", "anon"); //登录接口排除
filterChainDefinitionMap.put("/sys/mLogin", "anon"); //登录接口排除
filterChainDefinitionMap.put("/sys/logout", "anon"); //登出接口排除
filterChainDefinitionMap.put("/sys/getEncryptedString", "anon"); //获取加密串
filterChainDefinitionMap.put("/sys/sms", "anon");//短信验证码
@ -87,19 +113,13 @@ public class ShiroConfig {
filterChainDefinitionMap.put("/actuator/httptrace/**", "anon");
filterChainDefinitionMap.put("/actuator/redis/**", "anon");
filterChainDefinitionMap.put("/test/jeecgDemo/demo3", "anon"); //模板测试
filterChainDefinitionMap.put("/test/jeecgDemo/redisDemo/**", "anon"); //redis测试
//测试示例
filterChainDefinitionMap.put("/test/jeecgDemo/html", "anon"); //模板页面
filterChainDefinitionMap.put("/test/jeecgDemo/redis/**", "anon"); //redis测试
//排除Online请求
filterChainDefinitionMap.put("/auto/cgform/**", "anon");
//websocket排除
filterChainDefinitionMap.put("/websocket/**", "anon");
// 添加自己的过滤器并且取名为jwt
Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
filterMap.put("jwt", new JwtFilter());
@ -129,7 +149,8 @@ public class ShiroConfig {
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
securityManager.setSubjectDAO(subjectDAO);
//自定义缓存实现,使用redis
securityManager.setCacheManager(redisCacheManager());
return securityManager;
}
@ -146,7 +167,7 @@ public class ShiroConfig {
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@ -157,4 +178,38 @@ public class ShiroConfig {
return advisor;
}
/**
* cacheManager 缓存 redis实现
* 使用的是shiro-redis开源插件
*
* @return
*/
public RedisCacheManager redisCacheManager() {
log.info("===============(1)创建缓存管理器RedisCacheManager");
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
//redis中针对不同用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识)
redisCacheManager.setPrincipalIdFieldName("id");
//用户权限信息缓存时间
redisCacheManager.setExpire(200000);
return redisCacheManager;
}
/**
* 配置shiro redisManager
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisManager redisManager() {
log.info("===============(2)创建RedisManager,连接Redis..URL= " + host + ":" + port);
RedisManager redisManager = new RedisManager();
redisManager.setHost(host + ":" + port);//老版本是分别setHost和setPort,新版本只需要setHost就可以了
if (!StringUtils.isEmpty(redisPassword)) {
redisManager.setPassword(redisPassword);
}
return redisManager;
}
}

View File

@ -1,6 +1,7 @@
package org.jeecg.config;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -17,9 +18,14 @@ public class StaticConfig {
@Value("${jeecg.sms.accessKeySecret}")
private String accessKeySecret;
@Value(value = "${spring.mail.username}")
private String emailFrom;
@Bean
public void initStatic() {
DySmsHelper.setAccessKeyId(accessKeyId);
DySmsHelper.setAccessKeySecret(accessKeySecret);
EmailSendMsgHandle.setEmailFrom(emailFrom);
}
}

View File

@ -0,0 +1,35 @@
package org.jeecg.config.oss;
import org.jeecg.config.oss.OSSAutoConfiguration.OSSConfigurationImportSelector;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
/**
* Object Storage Service auto configuration.
*/
@Configuration
@EnableConfigurationProperties(OSSProperties.class)
@Import(OSSConfigurationImportSelector.class)
public class OSSAutoConfiguration {
/**
* {@link ImportSelector} to add {@link OSSType} configuration classes.
*/
static class OSSConfigurationImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
OSSType[] types = OSSType.values();
String[] imports = new String[types.length];
for (int i = 0; i < types.length; i++) {
imports[i] = OSSConfigurations.getConfigurationClass(types[i]);
}
return imports;
}
}
}

View File

@ -0,0 +1,43 @@
package org.jeecg.config.oss;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
/**
* General OSS condition used with all OSS configuration classes.
*/
public class OSSCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String sourceClass = "";
if (metadata instanceof ClassMetadata) {
sourceClass = ((ClassMetadata) metadata).getClassName();
}
ConditionMessage.Builder message = ConditionMessage.forCondition("OSS", sourceClass);
Environment environment = context.getEnvironment();
try {
BindResult<OSSType> specified = Binder.get(environment).bind("oss.type", OSSType.class);
if (!specified.isBound()) {
return ConditionOutcome.match(message.because("automatic OSS type"));
}
OSSType required = OSSConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
if (specified.get() == required) {
return ConditionOutcome.match(message.because(specified.get() + " OSS type"));
}
}
catch (BindException ex) {
}
return ConditionOutcome.noMatch(message.because("unknown OSS type"));
}
}

View File

@ -0,0 +1,44 @@
package org.jeecg.config.oss;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import org.jeecg.config.oss.aliyun.AliYunOSSAutoConfiguration;
import org.jeecg.config.oss.tencent.QcCOSAutoConfiguration;
import org.springframework.util.Assert;
/**
* Mappings between {@link OSSType} and {@code @Configuration}.
*/
final class OSSConfigurations {
private static final Map<OSSType, Class<?>> MAPPINGS;
static {
Map<OSSType, Class<?>> mappings = new EnumMap<>(OSSType.class);
mappings.put(OSSType.ALIYUN, AliYunOSSAutoConfiguration.class);
mappings.put(OSSType.QC, QcCOSAutoConfiguration.class);
MAPPINGS = Collections.unmodifiableMap(mappings);
}
private OSSConfigurations() {
}
public static String getConfigurationClass(OSSType ossType) {
Class<?> configurationClass = MAPPINGS.get(ossType);
Assert.state(configurationClass != null, () -> "Unknown OSS type " + ossType);
return configurationClass.getName();
}
public static OSSType getType(String configurationClassName) {
for (Map.Entry<OSSType, Class<?>> entry : MAPPINGS.entrySet()) {
if (entry.getValue().getName().equals(configurationClassName)) {
return entry.getKey();
}
}
throw new IllegalStateException("Unknown configuration class " + configurationClassName);
}
}

View File

@ -0,0 +1,15 @@
package org.jeecg.config.oss;
import java.io.InputStream;
/**
* 简单上传,删除对象接口.
* 可扩展
*/
public interface OSSManager {
void upload(String fileName, InputStream inputStream);
void delete(String fileName);
}

View File

@ -0,0 +1,48 @@
package org.jeecg.config.oss;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Configuration properties for OSS support.
*/
@Getter
@Setter
@ConfigurationProperties(prefix = "jeecg.oss")
public class OSSProperties {
/**
* OSS type.
*/
private OSSType type;
/**
* OSS Endpoint.
*/
private String endpoint;
/**
* OSS Access key.
*/
private String accessKey;
/**
* OSS Secret key.
*/
private String secretKey;
/**
* OSS Bucket Name.
*/
private String bucketName;
/**
* Additional OSS properties.
*/
private Map<String, String> properties = new HashMap<>();
}

View File

@ -0,0 +1,10 @@
package org.jeecg.config.oss;
/**
* Supported OSS types.
*/
public enum OSSType {
ALIYUN, QC
}

View File

@ -0,0 +1,81 @@
package org.jeecg.config.oss.aliyun;
import java.util.Map;
import java.util.Properties;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import org.jeecg.config.oss.OSSCondition;
import org.jeecg.config.oss.OSSManager;
import org.jeecg.config.oss.OSSProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* AliYun OSS configuration.
*/
@Configuration
@ConditionalOnClass({ OSS.class })
@ConditionalOnProperty(prefix = "jeecg.oss", name = "type",havingValue = "aliyun")
@Conditional(OSSCondition.class)
public class AliYunOSSAutoConfiguration {
private final OSSProperties properties;
public AliYunOSSAutoConfiguration(OSSProperties ossProperties) {
this.properties = ossProperties;
}
@Bean
@ConditionalOnMissingBean
public ClientBuilderConfiguration clientConfiguration(OSSProperties ossProperties) {
Properties properties = asProperties(ossProperties.getProperties());
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setMaxConnections(Integer.parseInt(properties.getProperty("aliyun.maxConnections", "5")));
configuration.setSocketTimeout(Integer.parseInt(properties.getProperty("aliyun.socketTimeout", "50000")));
configuration
.setConnectionTimeout(Integer.parseInt(properties.getProperty("aliyun.connectionTimeout", "50000")));
configuration.setConnectionRequestTimeout(
Integer.parseInt(properties.getProperty("aliyun.connectionRequestTimeout", "-1")));
configuration
.setIdleConnectionTime(Integer.parseInt(properties.getProperty("aliyun.idleConnectionTime", "60000")));
configuration.setMaxErrorRetry(Integer.parseInt(properties.getProperty("aliyun.maxErrorRetry", "3")));
configuration.setSupportCname(Boolean.parseBoolean(properties.getProperty("aliyun.supportCname", "false")));
configuration.setSLDEnabled(Boolean.parseBoolean(properties.getProperty("aliyun.sldEnabled", "false")));
configuration.setProtocol(Protocol.HTTP);
if (Protocol.HTTPS.toString().equals(properties.getProperty("aliyun.protocol"))) {
configuration.setProtocol(Protocol.HTTPS);
}
if (properties.getProperty("aliyun.userAgent") != null) {
configuration.setUserAgent(properties.getProperty("aliyun.userAgent"));
}
return configuration;
}
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
public OSS ossClient(ClientBuilderConfiguration clientConfiguration) {
return new OSSClientBuilder().build(this.properties.getEndpoint(), this.properties.getAccessKey(),
this.properties.getSecretKey(), clientConfiguration);
}
@Bean
@ConditionalOnMissingBean
public OSSManager ossManager(OSS ossClient) {
return new AliYunOSSManager(ossClient, this.properties);
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
}

View File

@ -0,0 +1,33 @@
package org.jeecg.config.oss.aliyun;
import java.io.InputStream;
import com.aliyun.oss.OSS;
import org.jeecg.config.oss.OSSManager;
import org.jeecg.config.oss.OSSProperties;
/**
* Object Storage Service of AliYun.
*/
public class AliYunOSSManager implements OSSManager {
private OSS client;
private OSSProperties properties;
AliYunOSSManager(OSS client, OSSProperties properties) {
this.client = client;
this.properties = properties;
}
@Override
public void upload(String fileName, InputStream inputStream) {
this.client.putObject(this.properties.getBucketName(), fileName, inputStream);
}
@Override
public void delete(String fileName) {
this.client.deleteObject(this.properties.getBucketName(), fileName);
}
}

View File

@ -0,0 +1,71 @@
package org.jeecg.config.oss.tencent;
import java.util.Map;
import java.util.Properties;
import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.jeecg.config.oss.OSSCondition;
import org.jeecg.config.oss.OSSManager;
import org.jeecg.config.oss.OSSProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnClass({ COS.class })
@ConditionalOnProperty(prefix = "jeecg.oss", name = "type",havingValue = "qc")
@Conditional(OSSCondition.class)
public class QcCOSAutoConfiguration {
private final OSSProperties properties;
public QcCOSAutoConfiguration(OSSProperties ossProperties) {
this.properties = ossProperties;
}
@Bean
@ConditionalOnMissingBean
public ClientConfig clientConfiguration(OSSProperties ossProperties) {
Properties properties = asProperties(ossProperties.getProperties());
ClientConfig configuration = new ClientConfig();
configuration.setMaxConnectionsCount(Integer.parseInt(properties.getProperty("qc.maxConnectionsCount", "5")));
configuration.setSocketTimeout(Integer.parseInt(properties.getProperty("qc.socketTimeout", "50000")));
configuration.setConnectionTimeout(Integer.parseInt(properties.getProperty("qc.connectionTimeout", "50000")));
configuration.setConnectionRequestTimeout(
Integer.parseInt(properties.getProperty("qc.connectionRequestTimeout", "-1")));
configuration.setRegion(new Region(properties.getProperty("qc.region")));
if (properties.getProperty("qc.userAgent") != null) {
configuration.setUserAgent(properties.getProperty("qc.userAgent"));
}
return configuration;
}
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
public COS ossClient(ClientConfig clientConfig) {
COSCredentials cred = new BasicCOSCredentials(this.properties.getAccessKey(), this.properties.getSecretKey());
return new COSClient(cred, clientConfig);
}
@Bean
@ConditionalOnMissingBean
public OSSManager ossManager(COS client) {
return new QcCOSManager(client, this.properties);
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
}

View File

@ -0,0 +1,39 @@
package org.jeecg.config.oss.tencent;
import java.io.InputStream;
import com.qcloud.cos.COS;
import com.qcloud.cos.model.ObjectMetadata;
import org.jeecg.config.oss.OSSManager;
import org.jeecg.config.oss.OSSProperties;
/**
* Object Storage Service of Tencent cloud.
*/
public class QcCOSManager implements OSSManager {
private COS client;
private OSSProperties properties;
QcCOSManager(COS client, OSSProperties properties) {
this.client = client;
this.properties = properties;
}
@Override
public void upload(String fileName, InputStream inputStream) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(10);
objectMetadata.setContentType("application/octet-stream");
this.client.putObject(this.properties.getBucketName(),
this.properties.getProperties().get("qc.prefix") + "/" + fileName, inputStream, objectMetadata);
}
@Override
public void delete(String fileName) {
this.client.deleteObject(this.properties.getBucketName(),
this.properties.getProperties().get("qc.prefix") + "/" + fileName);
}
}

View File

@ -79,10 +79,10 @@ public class CasClientController {
return result;
}
String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
// 设置超时时间
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
// 获取用户部门信息
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
//获取用户部门信息
JSONObject obj = new JSONObject();
List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
obj.put("departs", departs);

View File

@ -42,284 +42,254 @@ import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
/**
* @Description: 测试demo
* @Author: jeecg-boot
* @Date:2018-12-29
* @Version:V1.0
* @Description: 单表示例
* @Author: jeecg-boot
* @Date:2018-12-29
* @Version:V2.0
*/
@Slf4j
@Api(tags="单表DEMO")
@Api(tags = "单表DEMO")
@RestController
@RequestMapping("/test/jeecgDemo")
public class JeecgDemoController extends JeecgController<JeecgDemo,IJeecgDemoService> {
@Autowired
private IJeecgDemoService jeecgDemoService;
public class JeecgDemoController extends JeecgController<JeecgDemo, IJeecgDemoService> {
@Autowired
private IJeecgDemoService jeecgDemoService;
@Autowired
private RedisUtil redisUtil;
@Autowired
private RedisUtil redisUtil;
/**
* 分页列表查询
*
* @param jeecgDemo
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@ApiOperation(value = "获取Demo数据列表", notes = "获取所有Demo数据列表")
@GetMapping(value = "/list")
@PermissionData(pageComponent="jeecg/JeecgDemoList")
public Result<IPage<JeecgDemo>> list(JeecgDemo jeecgDemo, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
Result<IPage<JeecgDemo>> result = new Result<IPage<JeecgDemo>>();
/*
* QueryWrapper<JeecgDemo> queryWrapper = null;
* //===========================================================================
* ===== //高级组合查询 try { String superQueryParams =
* req.getParameter("superQueryParams");
* if(oConvertUtils.isNotEmpty(superQueryParams)) { // 解码 superQueryParams =
* URLDecoder.decode(superQueryParams, "UTF-8"); List<QueryRuleVo> userList =
* JSON.parseArray(superQueryParams, QueryRuleVo.class);
* log.info(superQueryParams); queryWrapper = new QueryWrapper<JeecgDemo>(); for
* (QueryRuleVo rule : userList) { if(oConvertUtils.isNotEmpty(rule.getField())
* && oConvertUtils.isNotEmpty(rule.getRule()) &&
* oConvertUtils.isNotEmpty(rule.getVal())){
* ObjectParseUtil.addCriteria(queryWrapper, rule.getField(),
* QueryRuleEnum.getByValue(rule.getRule()), rule.getVal()); } } } } catch
* (UnsupportedEncodingException e) { e.printStackTrace(); }
* //===========================================================================
* =====
*
* // 手工转换实体驼峰字段为下划线分隔表字段 queryWrapper = queryWrapper==null?new
* QueryWrapper<JeecgDemo>(jeecgDemo):queryWrapper; Page<JeecgDemo> page = new
* Page<JeecgDemo>(pageNo, pageSize);
*
* // 排序逻辑 处理 String column = req.getParameter("column"); String order =
* req.getParameter("order"); if (oConvertUtils.isNotEmpty(column) &&
* oConvertUtils.isNotEmpty(order)) { if ("asc".equals(order)) {
* queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column)); } else {
* queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column)); } }
*/
/**
* 分页列表查询
*
* @param jeecgDemo
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@ApiOperation(value = "获取Demo数据列表", notes = "获取所有Demo数据列表")
@GetMapping(value = "/list")
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
public Result<?> list(JeecgDemo jeecgDemo, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgDemo> queryWrapper = QueryGenerator.initQueryWrapper(jeecgDemo, req.getParameterMap());
Page<JeecgDemo> page = new Page<JeecgDemo>(pageNo, pageSize);
QueryWrapper<JeecgDemo> queryWrapper = QueryGenerator.initQueryWrapper(jeecgDemo, req.getParameterMap());
Page<JeecgDemo> page = new Page<JeecgDemo>(pageNo, pageSize);
IPage<JeecgDemo> pageList = jeecgDemoService.page(page, queryWrapper);
log.info("查询当前页:" + pageList.getCurrent());
log.info("查询当前页数量:" + pageList.getSize());
log.info("查询结果数量:" + pageList.getRecords().size());
log.info("数据总数:" + pageList.getTotal());
return Result.ok(pageList);
}
IPage<JeecgDemo> pageList = jeecgDemoService.page(page, queryWrapper);
// log.info("查询当前页:" + pageList.getCurrent());
// log.info("查询当前页数量:" + pageList.getSize());
// log.info("查询结果数量:" + pageList.getRecords().size());
// log.info("数据总数:" + pageList.getTotal());
result.setSuccess(true);
result.setResult(pageList);
return result;
}
/**
* 添加
*
* @param jeecgDemo
* @return
*/
@PostMapping(value = "/add")
@AutoLog(value = "添加测试DEMO")
@ApiOperation(value = "添加DEMO", notes = "添加DEMO")
public Result<?> add(@RequestBody JeecgDemo jeecgDemo) {
jeecgDemoService.save(jeecgDemo);
return Result.ok("添加成功!");
}
/**
* 添加
*
* @param jeecgDemo
* @return
*/
@PostMapping(value = "/add")
@AutoLog(value = "添加测试DEMO")
@ApiOperation(value = "添加DEMO", notes = "添加DEMO")
public Result<JeecgDemo> add(@RequestBody JeecgDemo jeecgDemo) {
Result<JeecgDemo> result = new Result<JeecgDemo>();
try {
jeecgDemoService.save(jeecgDemo);
result.success("添加成功!");
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("操作失败");
}
return result;
}
/**
* 编辑
*
* @param jeecgDemo
* @return
*/
@PutMapping(value = "/edit")
@ApiOperation(value = "编辑DEMO", notes = "编辑DEMO")
@AutoLog(value = "编辑DEMO", operateType = CommonConstant.OPERATE_TYPE_3)
public Result<?> edit(@RequestBody JeecgDemo jeecgDemo) {
jeecgDemoService.updateById(jeecgDemo);
return Result.ok("更新成功!");
}
/**
* 编辑
*
* @param jeecgDemo
* @return
*/
@PutMapping(value = "/edit")
@ApiOperation(value = "编辑DEMO", notes = "编辑DEMO")
@AutoLog(value = "编辑DEMO",operateType= CommonConstant.OPERATE_TYPE_3)
public Result<JeecgDemo> edit(@RequestBody JeecgDemo jeecgDemo) {
Result<JeecgDemo> result = new Result<JeecgDemo>();
JeecgDemo jeecgDemoEntity = jeecgDemoService.getById(jeecgDemo.getId());
if (jeecgDemoEntity == null) {
result.error500("未找到对应实体");
} else {
boolean ok = jeecgDemoService.updateById(jeecgDemo);
// TODO 返回false说明什么
if (ok) {
result.success("修改成功!");
}
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "删除测试DEMO")
@DeleteMapping(value = "/delete")
@ApiOperation(value = "通过ID删除DEMO", notes = "通过ID删除DEMO")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
jeecgDemoService.removeById(id);
return Result.ok("删除成功!");
}
return result;
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
@ApiOperation(value = "批量删除DEMO", notes = "批量删除DEMO")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.jeecgDemoService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "删除测试DEMO")
@DeleteMapping(value = "/delete")
@ApiOperation(value = "通过ID删除DEMO", notes = "通过ID删除DEMO")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
try {
jeecgDemoService.removeById(id);
} catch (Exception e) {
log.error("删除失败",e.getMessage());
return Result.error("删除失败!");
}
return Result.ok("删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
@ApiOperation(value = "通过ID查询DEMO", notes = "通过ID查询DEMO")
public Result<?> queryById(@ApiParam(name = "id", value = "示例id", required = true) @RequestParam(name = "id", required = true) String id) {
JeecgDemo jeecgDemo = jeecgDemoService.getById(id);
return Result.ok(jeecgDemo);
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
@ApiOperation(value = "批量删除DEMO", notes = "批量删除DEMO")
public Result<JeecgDemo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<JeecgDemo> result = new Result<JeecgDemo>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.jeecgDemoService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
/**
* 导出excel
*
* @param request
*/
@RequestMapping(value = "/exportXls")
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
public ModelAndView exportXls(HttpServletRequest request, JeecgDemo jeecgDemo) {
return super.exportXls(request, jeecgDemo, JeecgDemo.class, "单表模型");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
@ApiOperation(value = "通过ID查询DEMO", notes = "通过ID查询DEMO")
public Result<JeecgDemo> queryById(@ApiParam(name = "id", value = "示例id", required = true) @RequestParam(name = "id", required = true) String id) {
Result<JeecgDemo> result = new Result<JeecgDemo>();
JeecgDemo jeecgDemo = jeecgDemoService.getById(id);
if (jeecgDemo == null) {
result.error500("未找到对应实体");
} else {
result.setResult(jeecgDemo);
result.setSuccess(true);
}
return result;
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, JeecgDemo.class);
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
@PermissionData(pageComponent="jeecg/JeecgDemoList")
public ModelAndView exportXls(HttpServletRequest request, JeecgDemo jeecgDemo) {
return super.exportXls(request, jeecgDemo, JeecgDemo.class, "单表模型");
}
// =====Redis 示例===============================================================================================
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, JeecgDemo.class);
}
/**
* redis操作 -- set
*/
@GetMapping(value = "/redisSet")
public void redisSet() {
redisUtil.set("name", "张三" + DateUtils.now());
}
// ================================================================================================================
/**
* redis操作 -- set
*/
@GetMapping(value = "/redisSet")
public void redisSet() {
redisUtil.set("name", "张三" + DateUtils.now());
}
/**
* redis操作 -- get
*/
@GetMapping(value = "/redisGet")
public String redisGet() {
return (String) redisUtil.get("name");
}
/**
* redis操作 -- get
*/
@GetMapping(value = "/redisGet")
public String redisGet() {
return (String) redisUtil.get("name");
}
/**
* redis操作 -- setObj
*/
@GetMapping(value = "/redisSetObj")
public void redisSetObj() {
JeecgDemo p = new JeecgDemo();
p.setAge(10);
p.setBirthday(new Date());
p.setContent("hello");
p.setName("张三");
p.setSex("");
redisUtil.set("user-zdh", p);
}
/**
* redis操作 -- setObj
*/
@GetMapping(value = "/redisSetObj")
public void redisSetObj() {
JeecgDemo p = new JeecgDemo();
p.setAge(10);
p.setBirthday(new Date());
p.setContent("hello");
p.setName("张三");
p.setSex("");
redisUtil.set("user-zdh", p);
}
/**
* redis操作 -- setObj
*/
@GetMapping(value = "/redisGetObj")
public Object redisGetObj() {
return redisUtil.get("user-zdh");
}
/**
* redis操作 -- setObj
*/
@GetMapping(value = "/redisGetObj")
public Object redisGetObj() {
return redisUtil.get("user-zdh");
}
/**
* redis操作 -- get
*/
@GetMapping(value = "/redis/{id}")
public JeecgDemo redisGetJeecgDemo(@PathVariable("id") String id) {
JeecgDemo t = jeecgDemoService.getByIdCacheable(id);
log.info(t.toString());
return t;
}
/**
* redis操作 -- get
*/
@GetMapping(value = "/redisDemo/{id}")
public JeecgDemo redisGetJeecgDemo(@PathVariable("id") String id) {
JeecgDemo t = jeecgDemoService.getByIdCacheable(id);
System.out.println(t);
return t;
}
// ===Freemaker示例================================================================================
/**
* freemaker方式 【页面路径: src/main/resources/templates】
*
* @param modelAndView
* @return
*/
@RequestMapping("/demo3")
public ModelAndView demo3(ModelAndView modelAndView) {
modelAndView.setViewName("demo3");
List<String> userList = new ArrayList<String>();
userList.add("admin");
userList.add("user1");
userList.add("user2");
log.info("--------------test--------------");
modelAndView.addObject("userList", userList);
return modelAndView;
}
/**
* freemaker方式 【页面路径: src/main/resources/templates】
*
* @param modelAndView
* @return
*/
@RequestMapping("/html")
public ModelAndView ftl(ModelAndView modelAndView) {
modelAndView.setViewName("demo3");
List<String> userList = new ArrayList<String>();
userList.add("admin");
userList.add("user1");
userList.add("user2");
log.info("--------------test--------------");
modelAndView.addObject("userList", userList);
return modelAndView;
}
// ================================================================================================================
// ==========================================动态表单
// JSON接收测试===========================================//
@PostMapping(value = "/testOnlineAdd")
public Result<JeecgDemo> testOnlineAdd(@RequestBody JSONObject json) {
Result<JeecgDemo> result = new Result<JeecgDemo>();
log.info(json.toJSONString());
result.success("添加成功!");
return result;
}
// ==========================================动态表单 JSON接收测试===========================================
@PostMapping(value = "/testOnlineAdd")
public Result<?> testOnlineAdd(@RequestBody JSONObject json) {
log.info(json.toJSONString());
return Result.ok("添加成功!");
}
/*----------------------------------------外部获取权限示例------------------------------------*/
/**
* 【数据权限示例 - 编程】mybatisPlus java类方式加载权限
*
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/mpList")
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
public Result<?> loadMpPermissonList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>();
//编程方式给queryWrapper装载数据权限规则
QueryGenerator.installAuthMplus(queryWrapper, JeecgDemo.class);
Page<JeecgDemo> page = new Page<JeecgDemo>(pageNo, pageSize);
IPage<JeecgDemo> pageList = jeecgDemoService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 【数据权限示例 - 编程】mybatis xml方式加载权限
*
* @param jeecgDemo
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/sqlList")
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
public Result<?> loadSqlPermissonList(JeecgDemo jeecgDemo, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
IPage<JeecgDemo> pageList = jeecgDemoService.queryListWithPermission(pageSize, pageNo);
return Result.ok(pageList);
}
/*----------------------------------------外部获取权限示例------------------------------------*/
}

View File

@ -1,425 +0,0 @@
package org.jeecg.modules.demo.test.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.test.entity.JeecgOrderCustomer;
import org.jeecg.modules.demo.test.entity.JeecgOrderMain;
import org.jeecg.modules.demo.test.entity.JeecgOrderTicket;
import org.jeecg.modules.demo.test.service.IJeecgOrderCustomerService;
import org.jeecg.modules.demo.test.service.IJeecgOrderMainService;
import org.jeecg.modules.demo.test.service.IJeecgOrderTicketService;
import org.jeecg.modules.demo.test.vo.JeecgOrderMainPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
/**
* @Title: Controller
* @Description: 订单模拟
* @Author: ZhiLin
* @Date: 2019-02-20
* @Version: v1.0
*/
@Slf4j
@RestController
@RequestMapping("/test/order")
public class JeecgOrderDMainController {
@Autowired
private IJeecgOrderMainService jeecgOrderMainService;
@Autowired
private IJeecgOrderCustomerService jeecgOrderCustomerService;
@Autowired
private IJeecgOrderTicketService jeecgOrderTicketService;
@Autowired
private IJeecgOrderCustomerService customerService;
@Autowired
private IJeecgOrderTicketService ticketService;
/**
* 分页列表查询
*
* @param jeecgOrderMain
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/orderList")
public Result<IPage<JeecgOrderMain>> respondePagedData(JeecgOrderMain jeecgOrderMain,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
Result<IPage<JeecgOrderMain>> result = new Result<IPage<JeecgOrderMain>>();
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, req.getParameterMap());
Page<JeecgOrderMain> page = new Page<JeecgOrderMain>(pageNo, pageSize);
IPage<JeecgOrderMain> pageList = jeecgOrderMainService.page(page, queryWrapper);
//log.debug("查询当前页:"+pageList.getCurrent());
//log.debug("查询当前页数量:"+pageList.getSize());
//log.debug("查询结果数量:"+pageList.getRecords().size());
//log.debug("数据总数:"+pageList.getTotal());
result.setSuccess(true);
result.setResult(pageList);
return result;
}
/**
* 添加
*
* @param jeecgOrderMainPage
* @return
*/
@PostMapping(value = "/add")
public Result<JeecgOrderMain> add(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
try {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.save(jeecgOrderMain);
result.success("添加成功!");
} catch (Exception e) {
log.error(e.getMessage(),e);
result.error500("操作失败");
}
return result;
}
/**
* 编辑
*
* @param jeecgOrderMainPage
* @return
*/
@PutMapping("/edit")
public Result<JeecgOrderMain> edit(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
JeecgOrderMain jeecgOrderMainEntity = jeecgOrderMainService.getById(jeecgOrderMain.getId());
if (jeecgOrderMainEntity == null) {
result.error500("未找到对应实体");
} else {
jeecgOrderMainService.updateById(jeecgOrderMain);
result.success("修改成功!");
}
return result;
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<JeecgOrderMain> delete(@RequestParam(name = "id", required = true) String id) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
JeecgOrderMain jeecgOrderMain = jeecgOrderMainService.getById(id);
if (jeecgOrderMain == null) {
result.error500("未找到对应实体");
} else {
jeecgOrderMainService.delMain(id);
result.success("删除成功!");
}
return result;
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<JeecgOrderMain> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.jeecgOrderMainService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<JeecgOrderMain> queryById(@RequestParam(name = "id", required = true) String id) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
JeecgOrderMain jeecgOrderMain = jeecgOrderMainService.getById(id);
if (jeecgOrderMain == null) {
result.error500("未找到对应实体");
} else {
result.setResult(jeecgOrderMain);
result.setSuccess(true);
}
return result;
}
/**
* 通过id查询
*
* @param mainId
* @return
*/
@GetMapping(value = "/listOrderCustomerByMainId")
public Result<List<JeecgOrderCustomer>> queryOrderCustomerListByMainId(@RequestParam(name = "mainId", required = false) String mainId) {
Result<List<JeecgOrderCustomer>> result = new Result<List<JeecgOrderCustomer>>();
List<JeecgOrderCustomer> jeecgOrderCustomerList = null;
if (mainId != null) {
jeecgOrderCustomerList = jeecgOrderCustomerService.selectCustomersByMainId(mainId);
result.setResult(jeecgOrderCustomerList);
result.setSuccess(true);
return result;
} else {
return null;
}
}
/**
* 通过id查询
*
* @param mainId
* @return
*/
@GetMapping(value = "/listOrderTicketByMainId")
public Result<List<JeecgOrderTicket>> queryOrderTicketListByMainId(@RequestParam(name = "mainId", required = false) String mainId) {
Result<List<JeecgOrderTicket>> result = new Result<List<JeecgOrderTicket>>();
List<JeecgOrderTicket> jeecgOrderTicketList = null;
if (mainId != null) {
jeecgOrderTicketList = jeecgOrderTicketService.selectTicketsByMainId(mainId);
result.setResult(jeecgOrderTicketList);
result.setSuccess(true);
return result;
} else {
return null;
}
}
// ================================以下是客户信息相关的API=================================
/**
* 添加
*
* @param jeecgOrderCustomer
* @return
*/
@PostMapping(value = "/addCustomer")
public Result<JeecgOrderCustomer> addCustomer(@RequestBody JeecgOrderCustomer jeecgOrderCustomer) {
Result<JeecgOrderCustomer> result = new Result<>();
try {
boolean ok = customerService.save(jeecgOrderCustomer);
if (ok) {
result.setSuccess(true);
result.setMessage("添加数据成功");
} else {
result.setSuccess(false);
result.setMessage("添加数据失败");
}
return result;
} catch (Exception e) {
e.fillInStackTrace();
result.setSuccess(false);
result.setMessage("遇到问题了!");
return result;
}
}
/**
* 编辑
*
* @param jeecgOrderCustomer
* @return
*/
@PutMapping("/editCustomer")
public Result<JeecgOrderCustomer> editCustomer(@RequestBody JeecgOrderCustomer jeecgOrderCustomer) {
Result<JeecgOrderCustomer> result = new Result<>();
try {
boolean ok = customerService.updateById(jeecgOrderCustomer);
if (ok) {
result.setSuccess(true);
result.setMessage("更新成功");
} else {
result.setSuccess(false);
result.setMessage("更新失败");
}
return result;
} catch (Exception e) {
e.fillInStackTrace();
result.setSuccess(true);
result.setMessage("更新中碰到异常了");
return result;
}
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/deleteCustomer")
public Result<JeecgOrderCustomer> deleteCustomer(@RequestParam(name = "id", required = true) String id) {
Result<JeecgOrderCustomer> result = new Result<>();
try {
boolean ok = customerService.removeById(id);
if (ok) {
result.setSuccess(true);
result.setMessage("删除成功");
} else {
result.setSuccess(false);
result.setMessage("删除失败");
}
return result;
} catch (Exception e) {
e.fillInStackTrace();
result.setSuccess(false);
result.setMessage("删除过程中碰到异常了");
return result;
}
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatchCustomer")
public Result<JeecgOrderCustomer> deleteBatchCustomer(@RequestParam(name = "ids", required = true) String ids) {
Result<JeecgOrderCustomer> result = new Result<JeecgOrderCustomer>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.customerService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
//===========================以下是机票的相关API====================================
/**
* 添加
*
* @param jeecgOrderTicket
* @return
*/
@PostMapping(value = "/addTicket")
public Result<JeecgOrderTicket> addTicket(@RequestBody JeecgOrderTicket jeecgOrderTicket) {
Result<JeecgOrderTicket> result = new Result<>();
try {
boolean ok = ticketService.save(jeecgOrderTicket);
if (ok) {
result.setSuccess(true);
result.setMessage("添加机票信息成功.");
} else {
result.setSuccess(false);
result.setMessage("添加机票信息失败!");
}
return result;
} catch (Exception e) {
e.fillInStackTrace();
result.setSuccess(false);
result.setMessage("添加机票信息过程中出现了异常: " + e.getMessage());
return result;
}
}
/**
* 编辑
*
* @param jeecgOrderTicket
* @return
*/
@PutMapping("/editTicket")
public Result<JeecgOrderTicket> editTicket(@RequestBody JeecgOrderTicket jeecgOrderTicket) {
Result<JeecgOrderTicket> result = new Result<>();
try {
boolean ok = ticketService.updateById(jeecgOrderTicket);
if (ok) {
result.setSuccess(true);
result.setMessage("更新数据成功.");
} else {
result.setSuccess(false);
result.setMessage("更新机票 信息失败!");
}
return result;
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
return result;
}
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/deleteTicket")
public Result<JeecgOrderTicket> deleteTicket(@RequestParam(name = "id", required = true) String id) {
Result<JeecgOrderTicket> result = new Result<>();
try {
boolean ok = ticketService.removeById(id);
if (ok) {
result.setSuccess(true);
result.setMessage("删除机票信息成功.");
} else {
result.setSuccess(false);
result.setMessage("删除机票信息失败!");
}
return result;
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("删除机票信息过程中出现异常啦: " + e.getMessage());
return result;
}
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatchTicket")
public Result<JeecgOrderTicket> deleteBatchTicket(@RequestParam(name = "ids", required = true) String ids) {
Result<JeecgOrderTicket> result = new Result<JeecgOrderTicket>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.ticketService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
}

View File

@ -8,11 +8,17 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import org.jeecg.modules.demo.test.entity.JeecgOrderCustomer;
import org.jeecg.modules.demo.test.entity.JeecgOrderMain;
import org.jeecg.modules.demo.test.entity.JeecgOrderTicket;
import org.jeecg.modules.demo.test.service.IJeecgDemoService;
import org.jeecg.modules.demo.test.service.IJeecgOrderCustomerService;
import org.jeecg.modules.demo.test.service.IJeecgOrderMainService;
import org.jeecg.modules.demo.test.service.IJeecgOrderTicketService;
@ -44,250 +50,205 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
/**
* @Title: Controller
* @Description: 订单
* @Author: jeecg-boot
* @Date:2019-02-15
* @Version: V1.0
* @Description: 一对多示例JEditableTable行编辑
* @Author: jeecg-boot
* @Date:2019-02-15
* @Version: V2.0
*/
@RestController
@RequestMapping("/test/jeecgOrderMain")
@Slf4j
public class JeecgOrderMainController {
@Autowired
private IJeecgOrderMainService jeecgOrderMainService;
@Autowired
private IJeecgOrderCustomerService jeecgOrderCustomerService;
@Autowired
private IJeecgOrderTicketService jeecgOrderTicketService;
public class JeecgOrderMainController extends JeecgController<JeecgOrderMain, IJeecgOrderMainService> {
/**
* 分页列表查询
*
* @param jeecgOrderMain
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/list")
public Result<IPage<JeecgOrderMain>> queryPageList(JeecgOrderMain jeecgOrderMain, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
Result<IPage<JeecgOrderMain>> result = new Result<IPage<JeecgOrderMain>>();
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, req.getParameterMap());
Page<JeecgOrderMain> page = new Page<JeecgOrderMain>(pageNo, pageSize);
IPage<JeecgOrderMain> pageList = jeecgOrderMainService.page(page, queryWrapper);
// log.debug("查询当前页:"+pageList.getCurrent());
// log.debug("查询当前页数量:"+pageList.getSize());
// log.debug("查询结果数量:"+pageList.getRecords().size());
// log.debug("数据总数:"+pageList.getTotal());
result.setSuccess(true);
result.setResult(pageList);
return result;
}
@Autowired
private IJeecgOrderMainService jeecgOrderMainService;
@Autowired
private IJeecgOrderCustomerService jeecgOrderCustomerService;
@Autowired
private IJeecgOrderTicketService jeecgOrderTicketService;
/**
* 添加
*
* @param jeecgOrderMain
* @return
*/
@PostMapping(value = "/add")
public Result<JeecgOrderMain> add(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
try {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.saveMain(jeecgOrderMain, jeecgOrderMainPage.getJeecgOrderCustomerList(), jeecgOrderMainPage.getJeecgOrderTicketList());
result.success("添加成功!");
} catch (Exception e) {
log.error(e.getMessage(),e);
result.error500("操作失败");
}
return result;
}
/**
* 分页列表查询
*
* @param jeecgOrderMain
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/list")
public Result<?> queryPageList(JeecgOrderMain jeecgOrderMain, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, req.getParameterMap());
Page<JeecgOrderMain> page = new Page<JeecgOrderMain>(pageNo, pageSize);
IPage<JeecgOrderMain> pageList = jeecgOrderMainService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 编辑
*
* @param jeecgOrderMain
* @return
*/
@PutMapping(value = "/edit")
public Result<JeecgOrderMain> eidt(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
JeecgOrderMain jeecgOrderMainEntity = jeecgOrderMainService.getById(jeecgOrderMain.getId());
if (jeecgOrderMainEntity == null) {
result.error500("未找到对应实体");
} else {
jeecgOrderMainService.updateMain(jeecgOrderMain, jeecgOrderMainPage.getJeecgOrderCustomerList(), jeecgOrderMainPage.getJeecgOrderTicketList());
result.success("修改成功!");
}
/**
* 添加
*
* @param jeecgOrderMainPage
* @return
*/
@PostMapping(value = "/add")
public Result<?> add(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.saveMain(jeecgOrderMain, jeecgOrderMainPage.getJeecgOrderCustomerList(), jeecgOrderMainPage.getJeecgOrderTicketList());
return Result.ok("添加成功!");
}
return result;
}
/**
* 编辑
*
* @param jeecgOrderMainPage
* @return
*/
@PutMapping(value = "/edit")
public Result<?> eidt(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.updateMain(jeecgOrderMain, jeecgOrderMainPage.getJeecgOrderCustomerList(), jeecgOrderMainPage.getJeecgOrderTicketList());
return Result.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
try {
jeecgOrderMainService.delMain(id);
} catch (Exception e) {
log.error("删除失败",e.getMessage());
return Result.error("删除失败!");
}
return Result.ok("删除成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
jeecgOrderMainService.delMain(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<JeecgOrderMain> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.jeecgOrderMainService.delBatchMain(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.jeecgOrderMainService.delBatchMain(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<JeecgOrderMain> queryById(@RequestParam(name = "id", required = true) String id) {
Result<JeecgOrderMain> result = new Result<JeecgOrderMain>();
JeecgOrderMain jeecgOrderMain = jeecgOrderMainService.getById(id);
if (jeecgOrderMain == null) {
result.error500("未找到对应实体");
} else {
result.setResult(jeecgOrderMain);
result.setSuccess(true);
}
return result;
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
JeecgOrderMain jeecgOrderMain = jeecgOrderMainService.getById(id);
return Result.ok(jeecgOrderMain);
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryOrderCustomerListByMainId")
public Result<List<JeecgOrderCustomer>> queryOrderCustomerListByMainId(@RequestParam(name = "id", required = true) String id) {
Result<List<JeecgOrderCustomer>> result = new Result<List<JeecgOrderCustomer>>();
List<JeecgOrderCustomer> jeecgOrderCustomerList = jeecgOrderCustomerService.selectCustomersByMainId(id);
result.setResult(jeecgOrderCustomerList);
result.setSuccess(true);
return result;
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryOrderCustomerListByMainId")
public Result<?> queryOrderCustomerListByMainId(@RequestParam(name = "id", required = true) String id) {
List<JeecgOrderCustomer> jeecgOrderCustomerList = jeecgOrderCustomerService.selectCustomersByMainId(id);
return Result.ok(jeecgOrderCustomerList);
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryOrderTicketListByMainId")
public Result<List<JeecgOrderTicket>> queryOrderTicketListByMainId(@RequestParam(name = "id", required = true) String id) {
Result<List<JeecgOrderTicket>> result = new Result<List<JeecgOrderTicket>>();
List<JeecgOrderTicket> jeecgOrderTicketList = jeecgOrderTicketService.selectTicketsByMainId(id);
result.setResult(jeecgOrderTicketList);
result.setSuccess(true);
return result;
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryOrderTicketListByMainId")
public Result<?> queryOrderTicketListByMainId(@RequestParam(name = "id", required = true) String id) {
List<JeecgOrderTicket> jeecgOrderTicketList = jeecgOrderTicketService.selectTicketsByMainId(id);
return Result.ok(jeecgOrderTicketList);
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, JeecgOrderMain jeecgOrderMain) {
// Step.1 组装查询条件
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<JeecgOrderMainPage> pageList = new ArrayList<JeecgOrderMainPage>();
/**
* 导出excel
*
* @param request
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, JeecgOrderMain jeecgOrderMain) {
// Step.1 组装查询条件
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//获取当前用户
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
List<JeecgOrderMain> jeecgOrderMainList = jeecgOrderMainService.list(queryWrapper);
for (JeecgOrderMain orderMain : jeecgOrderMainList) {
JeecgOrderMainPage vo = new JeecgOrderMainPage();
BeanUtils.copyProperties(orderMain, vo);
// 查询机票
List<JeecgOrderTicket> jeecgOrderTicketList = jeecgOrderTicketService.selectTicketsByMainId(orderMain.getId());
vo.setJeecgOrderTicketList(jeecgOrderTicketList);
// 查询客户
List<JeecgOrderCustomer> jeecgOrderCustomerList = jeecgOrderCustomerService.selectCustomersByMainId(orderMain.getId());
vo.setJeecgOrderCustomerList(jeecgOrderCustomerList);
pageList.add(vo);
}
List<JeecgOrderMainPage> pageList = new ArrayList<JeecgOrderMainPage>();
// 导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "一对多导出文件名字");
// 注解对象Class
mv.addObject(NormalExcelConstants.CLASS, JeecgOrderMainPage.class);
// 自定义表格参数
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("自定义导出Excel内容标题", "导出人:Jeecg", "自定义Sheet名字"));
// 导出数据列表
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
List<JeecgOrderMain> jeecgOrderMainList = jeecgOrderMainService.list(queryWrapper);
for (JeecgOrderMain orderMain : jeecgOrderMainList) {
JeecgOrderMainPage vo = new JeecgOrderMainPage();
BeanUtils.copyProperties(orderMain, vo);
// 查询机票
List<JeecgOrderTicket> jeecgOrderTicketList = jeecgOrderTicketService.selectTicketsByMainId(orderMain.getId());
vo.setJeecgOrderTicketList(jeecgOrderTicketList);
// 查询客户
List<JeecgOrderCustomer> jeecgOrderCustomerList = jeecgOrderCustomerService.selectCustomersByMainId(orderMain.getId());
vo.setJeecgOrderCustomerList(jeecgOrderCustomerList);
pageList.add(vo);
}
/**
* 通过excel导入数据
*
* @param request
* @param
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(2);
params.setNeedSave(true);
try {
List<JeecgOrderMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), JeecgOrderMainPage.class, params);
for (JeecgOrderMainPage page : list) {
JeecgOrderMain po = new JeecgOrderMain();
BeanUtils.copyProperties(page, po);
jeecgOrderMainService.saveMain(po, page.getJeecgOrderCustomerList(), page.getJeecgOrderTicketList());
}
return Result.ok("文件导入成功!");
} catch (Exception e) {
log.error(e.getMessage(),e);
return Result.error("文件导入失败:"+e.getMessage());
} finally {
try {
file.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return Result.error("文件导入失败!");
}
// 导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "一对多订单示例");
// 注解对象Class
mv.addObject(NormalExcelConstants.CLASS, JeecgOrderMainPage.class);
// 自定义表格参数
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("自定义导出Excel内容标题", "导出人:" + sysUser.getRealname(), "自定义Sheet名字"));
// 导出数据列表
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
/**
* 通过excel导入数据
*
* @param request
* @param
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(2);
params.setNeedSave(true);
try {
List<JeecgOrderMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), JeecgOrderMainPage.class, params);
for (JeecgOrderMainPage page : list) {
JeecgOrderMain po = new JeecgOrderMain();
BeanUtils.copyProperties(page, po);
jeecgOrderMainService.saveMain(po, page.getJeecgOrderCustomerList(), page.getJeecgOrderTicketList());
}
return Result.ok("文件导入成功!");
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("文件导入失败:" + e.getMessage());
} finally {
try {
file.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return Result.error("文件导入失败!");
}
}

View File

@ -0,0 +1,267 @@
package org.jeecg.modules.demo.test.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.test.entity.JeecgOrderCustomer;
import org.jeecg.modules.demo.test.entity.JeecgOrderMain;
import org.jeecg.modules.demo.test.entity.JeecgOrderTicket;
import org.jeecg.modules.demo.test.service.IJeecgOrderCustomerService;
import org.jeecg.modules.demo.test.service.IJeecgOrderMainService;
import org.jeecg.modules.demo.test.service.IJeecgOrderTicketService;
import org.jeecg.modules.demo.test.vo.JeecgOrderMainPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
/**
* @Description: 一对多示例ERP TAB风格
* @Author: ZhiLin
* @Date: 2019-02-20
* @Version: v2.0
*/
@Slf4j
@RestController
@RequestMapping("/test/order")
public class JeecgOrderTabMainController {
@Autowired
private IJeecgOrderMainService jeecgOrderMainService;
@Autowired
private IJeecgOrderCustomerService jeecgOrderCustomerService;
@Autowired
private IJeecgOrderTicketService jeecgOrderTicketService;
/**
* 分页列表查询
*
* @param jeecgOrderMain
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/orderList")
public Result<?> respondePagedData(JeecgOrderMain jeecgOrderMain,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgOrderMain> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderMain, req.getParameterMap());
Page<JeecgOrderMain> page = new Page<JeecgOrderMain>(pageNo, pageSize);
IPage<JeecgOrderMain> pageList = jeecgOrderMainService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 添加
*
* @param jeecgOrderMainPage
* @return
*/
@PostMapping(value = "/add")
public Result<?> add(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.save(jeecgOrderMain);
return Result.ok("添加成功!");
}
/**
* 编辑
*
* @param jeecgOrderMainPage
* @return
*/
@PutMapping("/edit")
public Result<?> edit(@RequestBody JeecgOrderMainPage jeecgOrderMainPage) {
JeecgOrderMain jeecgOrderMain = new JeecgOrderMain();
BeanUtils.copyProperties(jeecgOrderMainPage, jeecgOrderMain);
jeecgOrderMainService.updateById(jeecgOrderMain);
return Result.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
jeecgOrderMainService.delMain(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.jeecgOrderMainService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
JeecgOrderMain jeecgOrderMain = jeecgOrderMainService.getById(id);
return Result.ok(jeecgOrderMain);
}
/**
* 通过id查询
*
* @param jeecgOrderCustomer
* @return
*/
@GetMapping(value = "/listOrderCustomerByMainId")
public Result<?> queryOrderCustomerListByMainId(JeecgOrderCustomer jeecgOrderCustomer,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgOrderCustomer> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderCustomer, req.getParameterMap());
Page<JeecgOrderCustomer> page = new Page<JeecgOrderCustomer>(pageNo, pageSize);
IPage<JeecgOrderCustomer> pageList = jeecgOrderCustomerService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 通过id查询
*
* @param jeecgOrderTicket
* @return
*/
@GetMapping(value = "/listOrderTicketByMainId")
public Result<?> queryOrderTicketListByMainId(JeecgOrderTicket jeecgOrderTicket,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgOrderTicket> queryWrapper = QueryGenerator.initQueryWrapper(jeecgOrderTicket, req.getParameterMap());
Page<JeecgOrderTicket> page = new Page<JeecgOrderTicket>(pageNo, pageSize);
IPage<JeecgOrderTicket> pageList = jeecgOrderTicketService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 添加
*
* @param jeecgOrderCustomer
* @return
*/
@PostMapping(value = "/addCustomer")
public Result<?> addCustomer(@RequestBody JeecgOrderCustomer jeecgOrderCustomer) {
jeecgOrderCustomerService.save(jeecgOrderCustomer);
return Result.ok("添加成功!");
}
/**
* 编辑
*
* @param jeecgOrderCustomer
* @return
*/
@PutMapping("/editCustomer")
public Result<?> editCustomer(@RequestBody JeecgOrderCustomer jeecgOrderCustomer) {
jeecgOrderCustomerService.updateById(jeecgOrderCustomer);
return Result.ok("添加成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/deleteCustomer")
public Result<?> deleteCustomer(@RequestParam(name = "id", required = true) String id) {
jeecgOrderCustomerService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatchCustomer")
public Result<?> deleteBatchCustomer(@RequestParam(name = "ids", required = true) String ids) {
this.jeecgOrderCustomerService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 添加
*
* @param jeecgOrderTicket
* @return
*/
@PostMapping(value = "/addTicket")
public Result<?> addTicket(@RequestBody JeecgOrderTicket jeecgOrderTicket) {
jeecgOrderTicketService.save(jeecgOrderTicket);
return Result.ok("添加成功!");
}
/**
* 编辑
*
* @param jeecgOrderTicket
* @return
*/
@PutMapping("/editTicket")
public Result<?> editTicket(@RequestBody JeecgOrderTicket jeecgOrderTicket) {
jeecgOrderTicketService.updateById(jeecgOrderTicket);
return Result.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/deleteTicket")
public Result<?> deleteTicket(@RequestParam(name = "id", required = true) String id) {
jeecgOrderTicketService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatchTicket")
public Result<?> deleteBatchTicket(@RequestParam(name = "ids", required = true) String ids) {
this.jeecgOrderTicketService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
}

View File

@ -24,7 +24,7 @@ public class JoaDemo implements Serializable {
private static final long serialVersionUID = 1L;
/**ID*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**请假人*/
@Excel(name = "请假人", width = 15)

View File

@ -1,9 +1,13 @@
package org.jeecg.modules.demo.test.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import org.springframework.data.repository.query.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
/**
* @Description: jeecg 测试demo
@ -14,5 +18,13 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface JeecgDemoMapper extends BaseMapper<JeecgDemo> {
public List<JeecgDemo> getDemoByName(@Param("name") String name);
/**
* 查询列表数据 直接传数据权限的sql进行数据过滤
* @param page
* @param permissionSql
* @return
*/
public IPage<JeecgDemo> queryListWithPermission(Page<JeecgDemo> page,@Param("permissionSql")String permissionSql);
}

View File

@ -6,4 +6,9 @@
<select id="getDemoByName" resultType="org.jeecg.modules.demo.test.entity.JeecgDemo">
select * from demo where name = #{name}
</select>
<!-- 根据权限sql查询数据集 -->
<select id="queryListWithPermission" parameterType="Object" resultType="org.jeecg.modules.demo.test.entity.JeecgDemo">
select * from demo where 1=1 ${permissionSql}
</select>
</mapper>

View File

@ -3,6 +3,8 @@ package org.jeecg.modules.demo.test.service;
import org.jeecg.common.system.base.service.JeecgService;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* @Description: jeecg 测试demo
* @Author: jeecg-boot
@ -14,4 +16,12 @@ public interface IJeecgDemoService extends JeecgService<JeecgDemo> {
public void testTran();
public JeecgDemo getByIdCacheable(String id);
/**
* 查询列表数据 在service中获取数据权限sql信息
* @param pageSize
* @param pageNo
* @return
*/
IPage<JeecgDemo> queryListWithPermission(int pageSize,int pageNo);
}

View File

@ -1,6 +1,10 @@
package org.jeecg.modules.demo.test.service.impl;
import org.jeecg.common.system.base.service.impl.JeecgServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import org.jeecg.modules.demo.test.mapper.JeecgDemoMapper;
import org.jeecg.modules.demo.test.service.IJeecgDemoService;
@ -16,7 +20,7 @@ import org.springframework.transaction.annotation.Transactional;
* @Version: V1.0
*/
@Service
public class JeecgDemoServiceImpl extends JeecgServiceImpl<JeecgDemoMapper, JeecgDemo> implements IJeecgDemoService {
public class JeecgDemoServiceImpl extends ServiceImpl<JeecgDemoMapper, JeecgDemo> implements IJeecgDemoService {
@Autowired
JeecgDemoMapper jeecgDemoMapper;
@ -51,7 +55,7 @@ public class JeecgDemoServiceImpl extends JeecgServiceImpl<JeecgDemoMapper, Jeec
* 缓存注解测试: redis
*/
@Override
@Cacheable(cacheNames="jeecgDemo", key="#id")
@Cacheable(cacheNames = CacheConstant.TEST_DEMO_CACHE, key = "#id")
public JeecgDemo getByIdCacheable(String id) {
JeecgDemo t = jeecgDemoMapper.selectById(id);
System.err.println("---未读缓存,读取数据库---");
@ -59,4 +63,13 @@ public class JeecgDemoServiceImpl extends JeecgServiceImpl<JeecgDemoMapper, Jeec
return t;
}
@Override
public IPage<JeecgDemo> queryListWithPermission(int pageSize,int pageNo) {
Page<JeecgDemo> page = new Page<>(pageNo, pageSize);
//编程方式获取当前请求的数据权限规则SQL片段
String sql = QueryGenerator.installAuthJdbc(JeecgDemo.class);
return this.baseMapper.queryListWithPermission(page, sql);
}
}

View File

@ -5,7 +5,6 @@ import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
@ -51,15 +50,12 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@GetMapping(value = "/list")
public Result<IPage<SysMessage>> queryPageList(SysMessage sysMessage, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
public Result<?> queryPageList(SysMessage sysMessage, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
Result<IPage<SysMessage>> result = new Result<IPage<SysMessage>>();
QueryWrapper<SysMessage> queryWrapper = QueryGenerator.initQueryWrapper(sysMessage, req.getParameterMap());
Page<SysMessage> page = new Page<SysMessage>(pageNo, pageSize);
IPage<SysMessage> pageList = sysMessageService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
return Result.ok(pageList);
}
/**
@ -69,16 +65,9 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@PostMapping(value = "/add")
public Result<T> add(@RequestBody SysMessage sysMessage) {
Result<T> result = new Result<T>();
try {
sysMessageService.save(sysMessage);
result.success("添加成功!");
} catch (Exception e) {
log.info(e.getMessage(), e);
result.error500("操作失败");
}
return result;
public Result<?> add(@RequestBody SysMessage sysMessage) {
sysMessageService.save(sysMessage);
return Result.ok("添加成功!");
}
/**
@ -88,20 +77,10 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@PutMapping(value = "/edit")
public Result<T> edit(@RequestBody SysMessage sysMessage) {
Result<T> result = new Result<T>();
SysMessage sysMessageEntity = sysMessageService.getById(sysMessage.getId());
if (sysMessageEntity == null) {
result.error500("未找到对应实体");
} else {
boolean ok = sysMessageService.updateById(sysMessage);
if (ok) {
result.success("修改成功!");
} else {
result.error500("修改失败!");
}
}
return result;
public Result<?> edit(@RequestBody SysMessage sysMessage) {
sysMessageService.updateById(sysMessage);
return Result.ok("修改成功!");
}
/**
@ -111,18 +90,9 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@DeleteMapping(value = "/delete")
public Result<T> delete(@RequestParam(name = "id", required = true) String id) {
Result<T> result = new Result<T>();
SysMessage sysMessage = sysMessageService.getById(id);
if (sysMessage == null) {
result.error500("未找到对应实体");
} else {
boolean ok = sysMessageService.removeById(id);
if (ok) {
result.success("删除成功!");
}
}
return result;
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysMessageService.removeById(id);
return Result.ok("删除成功!");
}
/**
@ -132,15 +102,10 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<T> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<T> result = new Result<T>();
if (ids == null || "".equals(ids.trim())) {
result.error500("ids参数不允许为空");
} else {
this.sysMessageService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysMessageService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功");
}
/**
@ -150,23 +115,15 @@ public class SysMessageController extends JeecgController<SysMessage, ISysMessag
* @return
*/
@GetMapping(value = "/queryById")
public Result<SysMessage> queryById(@RequestParam(name = "id", required = true) String id) {
Result<SysMessage> result = new Result<SysMessage>();
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessage sysMessage = sysMessageService.getById(id);
if (sysMessage == null) {
result.error500("未找到对应实体");
} else {
result.setResult(sysMessage);
result.setSuccess(true);
}
return result;
return Result.ok(sysMessage);
}
/**
* 导出excel
*
* @param request
* @param response
*/
@GetMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) {

View File

@ -6,7 +6,6 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
@ -57,15 +56,12 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@GetMapping(value = "/list")
public Result<IPage<SysMessageTemplate>> queryPageList(SysMessageTemplate sysMessageTemplate, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
public Result<?> queryPageList(SysMessageTemplate sysMessageTemplate, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
Result<IPage<SysMessageTemplate>> result = new Result<IPage<SysMessageTemplate>>();
QueryWrapper<SysMessageTemplate> queryWrapper = QueryGenerator.initQueryWrapper(sysMessageTemplate, req.getParameterMap());
Page<SysMessageTemplate> page = new Page<SysMessageTemplate>(pageNo, pageSize);
IPage<SysMessageTemplate> pageList = sysMessageTemplateService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
return Result.ok(pageList);
}
/**
@ -75,16 +71,9 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@PostMapping(value = "/add")
public Result<T> add(@RequestBody SysMessageTemplate sysMessageTemplate) {
Result<T> result = new Result<T>();
try {
sysMessageTemplateService.save(sysMessageTemplate);
result.success("添加成功!");
} catch (Exception e) {
log.info(e.getMessage(), e);
result.error500("操作失败");
}
return result;
public Result<?> add(@RequestBody SysMessageTemplate sysMessageTemplate) {
sysMessageTemplateService.save(sysMessageTemplate);
return Result.ok("添加成功!");
}
/**
@ -94,21 +83,9 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@PutMapping(value = "/edit")
public Result<T> edit(@RequestBody SysMessageTemplate sysMessageTemplate) {
Result<T> result = new Result<T>();
SysMessageTemplate sysMessageTemplateEntity = sysMessageTemplateService.getById(sysMessageTemplate.getId());
if (sysMessageTemplateEntity == null) {
result.error500("未找到对应实体");
} else {
boolean ok = sysMessageTemplateService.updateById(sysMessageTemplate);
if (ok) {
result.success("修改成功!");
} else {
result.error500("修改失败!");
}
}
return result;
public Result<?> edit(@RequestBody SysMessageTemplate sysMessageTemplate) {
sysMessageTemplateService.updateById(sysMessageTemplate);
return Result.ok("更新成功!");
}
/**
@ -118,19 +95,9 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@DeleteMapping(value = "/delete")
public Result<T> delete(@RequestParam(name = "id", required = true) String id) {
Result<T> result = new Result<T>();
SysMessageTemplate sysMessageTemplate = sysMessageTemplateService.getById(id);
if (sysMessageTemplate == null) {
result.error500("未找到对应实体");
} else {
boolean ok = sysMessageTemplateService.removeById(id);
if (ok) {
result.success("删除成功!");
}
}
return result;
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysMessageTemplateService.removeById(id);
return Result.ok("删除成功!");
}
/**
@ -140,15 +107,9 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<T> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<T> result = new Result<T>();
if (ids == null || "".equals(ids.trim())) {
result.error500("ids参数不允许为空");
} else {
this.sysMessageTemplateService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysMessageTemplateService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
@ -158,16 +119,9 @@ public class SysMessageTemplateController extends JeecgController<SysMessageTemp
* @return
*/
@GetMapping(value = "/queryById")
public Result<SysMessageTemplate> queryById(@RequestParam(name = "id", required = true) String id) {
Result<SysMessageTemplate> result = new Result<SysMessageTemplate>();
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessageTemplate sysMessageTemplate = sysMessageTemplateService.getById(id);
if (sysMessageTemplate == null) {
result.error500("未找到对应实体");
} else {
result.setResult(sysMessageTemplate);
result.setSuccess(true);
}
return result;
return Result.ok(sysMessageTemplate);
}
/**

View File

@ -6,13 +6,17 @@ import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
public class EmailSendMsgHandle implements ISendMsgHandle {
static String emailFrom;
public static void setEmailFrom(String emailFrom) {
EmailSendMsgHandle.emailFrom = emailFrom;
}
@Override
public void SendMsg(String es_receiver, String es_title, String es_content) {
JavaMailSender mailSender = (JavaMailSender) SpringContextUtils.getBean("mailSender");
SimpleMailMessage message = new SimpleMailMessage();
// 设置发送方邮箱地址
message.setFrom("2897976540@qq.com");
message.setFrom(emailFrom);
message.setTo(es_receiver);
message.setSubject(es_title);
message.setText(es_content);

View File

@ -13,6 +13,8 @@ import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
@Component
@ -48,7 +50,11 @@ public class WebSocket {
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端消息:"+message);
//log.info("【websocket消息】收到客户端消息:"+message);
JSONObject obj = new JSONObject();
obj.put("cmd", "heartcheck");//业务类型
obj.put("msgTxt", "心跳响应");//消息内容
session.getAsyncRemote().sendText(obj.toJSONString());
}
// 此为广播消息

View File

@ -0,0 +1,95 @@
package org.jeecg.modules.oss.controller;
import javax.servlet.http.HttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.oss.entity.OSSFile;
import org.jeecg.modules.oss.service.IOSSFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@Controller
@RequestMapping("/oss/file")
public class OSSFileController {
@Autowired
private IOSSFileService ossFileService;
@ResponseBody
@GetMapping("/list")
public Result<IPage<OSSFile>> queryPageList(OSSFile file,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
Result<IPage<OSSFile>> result = new Result<>();
QueryWrapper<OSSFile> queryWrapper = QueryGenerator.initQueryWrapper(file, req.getParameterMap());
Page<OSSFile> page = new Page<>(pageNo, pageSize);
IPage<OSSFile> pageList = ossFileService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
}
@ResponseBody
@PostMapping("/upload")
public Result upload(@RequestParam("file") MultipartFile multipartFile) {
Result result = new Result();
try {
ossFileService.upload(multipartFile);
result.success("上传成功!");
}
catch (Exception ex) {
log.info(ex.getMessage(), ex);
result.error500("上传失败");
}
return result;
}
@ResponseBody
@DeleteMapping("/delete")
public Result delete(@RequestParam(name = "id") String id) {
Result result = new Result();
OSSFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}
else {
boolean ok = ossFileService.delete(file);
if (ok) {
result.success("删除成功!");
}
}
return result;
}
/**
* 通过id查询.
*/
@ResponseBody
@GetMapping("/queryById")
public Result<OSSFile> queryById(@RequestParam(name = "id") String id) {
Result<OSSFile> result = new Result<>();
OSSFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}
else {
result.setResult(file);
result.setSuccess(true);
}
return result;
}
}

View File

@ -0,0 +1,24 @@
package org.jeecg.modules.oss.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.jeecg.common.system.base.entity.JeecgEntity;
import org.jeecgframework.poi.excel.annotation.Excel;
@Data
@TableName("oss_file")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class OSSFile extends JeecgEntity {
private static final long serialVersionUID = 1L;
@Excel(name = "文件名称")
private String fileName;
@Excel(name = "文件地址")
private String url;
}

View File

@ -0,0 +1,8 @@
package org.jeecg.modules.oss.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.oss.entity.OSSFile;
public interface OSSFileMapper extends BaseMapper<OSSFile> {
}

View File

@ -0,0 +1,15 @@
package org.jeecg.modules.oss.service;
import java.io.IOException;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.oss.entity.OSSFile;
import org.springframework.web.multipart.MultipartFile;
public interface IOSSFileService extends IService<OSSFile> {
void upload(MultipartFile multipartFile) throws IOException;
boolean delete(OSSFile ossFile);
}

View File

@ -0,0 +1,46 @@
package org.jeecg.modules.oss.service.impl;
import java.io.IOException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.config.oss.OSSManager;
import org.jeecg.config.oss.OSSProperties;
import org.jeecg.modules.oss.entity.OSSFile;
import org.jeecg.modules.oss.mapper.OSSFileMapper;
import org.jeecg.modules.oss.service.IOSSFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service("ossFileService")
public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> implements IOSSFileService {
@Autowired
private OSSManager ossManager;
@Autowired
private OSSProperties properties;
@Override
public void upload(MultipartFile multipartFile) throws IOException {
String fileName = multipartFile.getOriginalFilename();
OSSFile ossFile = new OSSFile();
ossFile.setFileName(fileName);
ossFile.setUrl("https://" + properties.getBucketName() + "." + properties.getEndpoint() + "/" + fileName);
this.save(ossFile);
ossManager.upload(fileName, multipartFile.getInputStream());
}
@Override
public boolean delete(OSSFile ossFile) {
try {
this.removeById(ossFile.getId());
ossManager.delete(ossFile.getFileName());
}
catch (Exception ex) {
return false;
}
return true;
}
}

View File

@ -1,8 +1,6 @@
package org.jeecg.modules.quartz.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@ -14,7 +12,6 @@ import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
@ -36,7 +33,6 @@ import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
@ -72,15 +68,13 @@ public class QuartzJobController {
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public Result<IPage<QuartzJob>> queryPageList(QuartzJob quartzJob, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
public Result<?> queryPageList(QuartzJob quartzJob, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
Result<IPage<QuartzJob>> result = new Result<IPage<QuartzJob>>();
QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, req.getParameterMap());
Page<QuartzJob> page = new Page<QuartzJob>(pageNo, pageSize);
IPage<QuartzJob> pageList = quartzJobService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
return Result.ok(pageList);
}
/**
@ -91,22 +85,12 @@ public class QuartzJobController {
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public Result<?> add(@RequestBody QuartzJob quartzJob) {
Result<QuartzJob> result = new Result<QuartzJob>();
List<QuartzJob> list = quartzJobService.findByJobClassName(quartzJob.getJobClassName());
if (list != null && list.size() > 0) {
return Result.error("该定时任务类名已存在");
}
try {
boolean ok = quartzJobService.saveAndScheduleJob(quartzJob);
if (ok) {
result.success("创建定时任务成功");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("创建定时任务失败," + e.getMessage());
}
return result;
quartzJobService.saveAndScheduleJob(quartzJob);
return Result.ok("创建定时任务成功");
}
/**
@ -117,23 +101,13 @@ public class QuartzJobController {
*/
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
public Result<?> eidt(@RequestBody QuartzJob quartzJob) {
Result<QuartzJob> result = new Result<QuartzJob>();
QuartzJob quartzJobEntity = quartzJobService.getById(quartzJob.getId());
if (quartzJobEntity == null) {
result.error500("未找到对应实体");
} else {
boolean ok = true;
try {
ok = quartzJobService.editAndScheduleJob(quartzJob);
} catch (SchedulerException e) {
log.error(e.getMessage(),e);
return Result.error("更新定时任务失败!");
}
if (ok) {
result.success("更新定时任务成功!");
}
try {
quartzJobService.editAndScheduleJob(quartzJob);
} catch (SchedulerException e) {
log.error(e.getMessage(),e);
return Result.error("更新定时任务失败!");
}
return result;
return Result.ok("更新定时任务成功!");
}
/**
@ -143,19 +117,14 @@ public class QuartzJobController {
* @return
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result<QuartzJob> delete(@RequestParam(name = "id", required = true) String id) {
Result<QuartzJob> result = new Result<QuartzJob>();
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
QuartzJob quartzJob = quartzJobService.getById(id);
if (quartzJob == null) {
result.error500("未找到对应实体");
} else {
boolean ok = quartzJobService.deleteAndStopJob(quartzJob);
if (ok) {
result.success("删除成功!");
}
return Result.error("未找到对应实体");
}
quartzJobService.deleteAndStopJob(quartzJob);
return Result.ok("删除成功!");
return result;
}
/**
@ -165,18 +134,15 @@ public class QuartzJobController {
* @return
*/
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
public Result<QuartzJob> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<QuartzJob> result = new Result<QuartzJob>();
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
for (String id : Arrays.asList(ids.split(","))) {
QuartzJob job = quartzJobService.getById(id);
quartzJobService.deleteAndStopJob(job);
}
result.success("删除定时任务成功!");
return Result.error("参数不识别!");
}
return result;
for (String id : Arrays.asList(ids.split(","))) {
QuartzJob job = quartzJobService.getById(id);
quartzJobService.deleteAndStopJob(job);
}
return Result.ok("删除定时任务成功!");
}
/**
@ -228,16 +194,9 @@ public class QuartzJobController {
* @return
*/
@RequestMapping(value = "/queryById", method = RequestMethod.GET)
public Result<QuartzJob> queryById(@RequestParam(name = "id", required = true) String id) {
Result<QuartzJob> result = new Result<QuartzJob>();
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
QuartzJob quartzJob = quartzJobService.getById(id);
if (quartzJob == null) {
result.error500("未找到对应实体");
} else {
result.setResult(quartzJob);
result.setSuccess(true);
}
return result;
return Result.ok(quartzJob);
}
/**

View File

@ -25,7 +25,7 @@ public class QuartzJob implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**创建人*/
private java.lang.String createBy;

View File

@ -11,6 +11,7 @@ import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
@ -40,6 +41,9 @@ public class ShiroRealm extends AuthorizingRealm {
private ISysUserService sysUserService;
@Autowired
@Lazy
private ISysBaseAPI sysBaseAPI;
@Autowired
@Lazy
private RedisUtil redisUtil;
/**
@ -51,18 +55,18 @@ public class ShiroRealm extends AuthorizingRealm {
}
/**
* 功能: 获取用户权限信息包括角色以及权限。只有当触发检测用户权限时才会调用此方法例如checkRole,checkPermission
*
* @param token token
* 权限信息认证(包括角色以及权限)是用户访问controller的时候才进行验证(redis存储的此处权限信息)
* 触发检测用户权限时才会调用此方法例如checkRole,checkPermission
*
* @param principals 身份信息
* @return AuthorizationInfo 权限信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
log.info("————权限认证 [ roles、permissions]————");
LoginUser sysUser = null;
log.info("===============Shiro权限认证开始============ [ roles、permissions]==========");
String username = null;
if (principals != null) {
sysUser = (LoginUser) principals.getPrimaryPrincipal();
LoginUser sysUser = (LoginUser) principals.getPrimaryPrincipal();
username = sysUser.getUsername();
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
@ -74,14 +78,17 @@ public class ShiroRealm extends AuthorizingRealm {
// 设置用户拥有的权限集合比如“sys:role:add,sys:user:add”
Set<String> permissionSet = sysUserService.getUserPermissionsSet(username);
info.addStringPermissions(permissionSet);
log.info("===============Shiro权限认证成功==============");
return info;
}
/**
* 功能: 用来进行身份认证,也就是说验证用户输入的账号和密码是否正确,获取身份验证信息,错误抛出异常
*
* @param authenticationToken 用户身份信息 token
* 用户信息认证是在用户进行登录的时候进行验证(不存redis)
* 也就是说验证用户输入的账号和密码是否正确,错误抛出异常
*
* @param auth 用户登录的账号密码信息
* @return 返回封装了用户信息的 AuthenticationInfo 实例
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
@ -97,7 +104,7 @@ public class ShiroRealm extends AuthorizingRealm {
/**
* 校验token的有效性
*
*
* @param token
*/
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
@ -108,36 +115,32 @@ public class ShiroRealm extends AuthorizingRealm {
}
// 查询用户信息
LoginUser loginUser = new LoginUser();
SysUser sysUser = sysUserService.getUserByName(username);
if (sysUser == null) {
log.info("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
LoginUser loginUser = sysBaseAPI.getUserByName(username);
if (loginUser == null) {
throw new AuthenticationException("用户不存在!");
}
// 判断用户状态
if (loginUser.getStatus() != 1) {
throw new AuthenticationException("账号已被锁定,请联系管理员!");
}
// 校验token是否超时失效 & 或者账号密码是否错误
if (!jwtTokenRefresh(token, username, sysUser.getPassword())) {
if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
throw new AuthenticationException("Token失效请重新登录!");
}
// 判断用户状态
if (sysUser.getStatus() != 1) {
throw new AuthenticationException("账号已被锁定,请联系管理员!");
}
BeanUtils.copyProperties(sysUser, loginUser);
return loginUser;
}
/**
* JWTToken刷新生命周期 解决用户一直在线操作提供Token失效问题
* 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样)
* JWTToken刷新生命周期 实现: 用户在线操作不掉线功能
* 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样)缓存有效期设置为Jwt有效时间的2倍
* 2、当该用户再次请求时通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
* 3、当该用户这次请求JWTToken值还在生命周期内则会通过重新PUT的方式k、v都为Token值缓存中的token值生命周期时间重新计算(这时候k、v值一样)
* 4、当该用户这次请求jwt生成的token值已经超时但该token对应cache中的k还是存在则表示该用户一直在操作只是JWT的token失效了程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值该缓存生命周期重新计算
* 5、当该用户这次请求jwt在生成的token值已经超时并在cache中不存在对应的k则表示该用户账户空闲超时返回用户信息已失效请重新登录
* 6、每次当返回为true情况下都会给Response的Header中设置Authorization该Authorization映射的v为cache对应的v值
* 7、注当前端接收到Response的Header中的Authorization值会存储起来作为以后请求token使用
* 参考方案https://blog.csdn.net/qq394829044/article/details/82763936
*
* 3、当该用户这次请求jwt生成的token值已经超时但该token对应cache中的k还是存在则表示该用户一直在操作只是JWT的token失效了程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值该缓存生命周期重新计算
* 4、当该用户这次请求jwt生成的token值已经超时并在cache中不存在对应的k则表示该用户账户空闲超时返回用户信息已失效请重新登录。
* 注意: 前端请求Header中设置Authorization保持不变校验有效性以缓存中的token为准
* 用户过期时间 = Jwt有效时间 * 2
*
* @param userName
* @param passWord
* @return
@ -148,17 +151,31 @@ public class ShiroRealm extends AuthorizingRealm {
// 校验token有效性
if (!JwtUtil.verify(cacheToken, userName, passWord)) {
String newAuthorization = JwtUtil.sign(userName, passWord);
// 设置超时时间
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
// 设置超时时间
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
} else {
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
// 设置超时时间
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
log.info("——————————用户在线操作更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
}
//update-begin--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
// else {
// // 设置超时时间
// redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
// redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
// }
//update-end--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
return true;
}
return false;
}
/**
* 清除当前用户的权限认证缓存
*
* @param principals 权限信息
*/
@Override
public void clearCache(PrincipalCollection principals) {
super.clearCache(principals);
}
}

View File

@ -1,6 +1,7 @@
package org.jeecg.modules.system.aspect;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@ -62,13 +63,13 @@ public class PermissionDataAspect {
Method method = signature.getMethod();
PermissionData pd = method.getAnnotation(PermissionData.class);
String component = pd.pageComponent();
SysPermission currentSyspermission=null;
List<SysPermission> currentSyspermission = null;
if(oConvertUtils.isNotEmpty(component)) {
//1.通过注解属性pageComponent 获取菜单
LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
query.eq(SysPermission::getDelFlag,0);
query.eq(SysPermission::getComponent, component);
currentSyspermission = sysPermissionService.getOne(query);
currentSyspermission = sysPermissionService.list(query);
}else {
String requestMethod = request.getMethod();
String requestPath = request.getRequestURI().substring(request.getContextPath().length());
@ -79,28 +80,31 @@ public class PermissionDataAspect {
query.eq(SysPermission::getMenuType,2);
query.eq(SysPermission::getDelFlag,0);
query.eq(SysPermission::getUrl, requestPath);
currentSyspermission = sysPermissionService.getOne(query);
currentSyspermission = sysPermissionService.list(query);
//2.未找到 再通过正则匹配获取菜单
if(currentSyspermission==null) {
if(currentSyspermission==null || currentSyspermission.size()==0) {
String regUrl = getRegexpUrl(requestPath);
if(regUrl!=null) {
currentSyspermission = sysPermissionService.getOne(new LambdaQueryWrapper<SysPermission>().eq(SysPermission::getMenuType,2).eq(SysPermission::getUrl, regUrl).eq(SysPermission::getDelFlag,0));
currentSyspermission = sysPermissionService.list(new LambdaQueryWrapper<SysPermission>().eq(SysPermission::getMenuType,2).eq(SysPermission::getUrl, regUrl).eq(SysPermission::getDelFlag,0));
}
}
}
//3.通过用户名+菜单ID 找到权限配置信息 放到request中去
if(currentSyspermission!=null) {
if(currentSyspermission!=null && currentSyspermission.size()>0) {
String username = JwtUtil.getUserNameByToken(request);
List<SysPermissionDataRule> dataRules = sysPermissionDataRuleService.queryPermissionDataRules(username, currentSyspermission.getId());
List<SysPermissionDataRule> dataRules = new ArrayList<SysPermissionDataRule>();
for (SysPermission sysPermission : currentSyspermission) {
List<SysPermissionDataRule> temp = sysPermissionDataRuleService.queryPermissionDataRules(username, sysPermission.getId());
if(temp!=null && temp.size()>0) {
dataRules.addAll(temp);
}
}
if(dataRules!=null && dataRules.size()>0) {
JeecgDataAutorUtils.installDataSearchConditon(request, dataRules);
//TODO 此处将用户信息查找出来放到request中实属无奈 可以优化
SysUserCacheInfo userinfo = sysUserService.getCacheUser(username);
JeecgDataAutorUtils.installUserInfo(request, userinfo);
}
}
return point.proceed();
}

View File

@ -1,26 +1,19 @@
package org.jeecg.modules.system.controller;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.*;
import org.jeecg.common.util.encryption.EncryptedString;
import org.jeecg.modules.shiro.vo.DefContants;
import org.jeecg.modules.system.entity.SysDepart;
@ -30,20 +23,11 @@ import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysLogService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* @Author scott
@ -64,10 +48,12 @@ public class LoginController {
private RedisUtil redisUtil;
@Autowired
private ISysDepartService sysDepartService;
private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ApiOperation("登录接口")
public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel) throws Exception {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel){
Result<JSONObject> result = new Result<JSONObject>();
String username = sysLoginModel.getUsername();
String password = sysLoginModel.getPassword();
@ -76,6 +62,18 @@ public class LoginController {
//password = AesEncryptUtil.desEncrypt(sysLoginModel.getPassword().replaceAll("%2B", "\\+")).trim();//密码解密
//update-begin--Author:scott Date:20190805 for暂时注释掉密码加密逻辑有点问题
//update-begin-author:taoyan date:20190828 for:校验验证码
Object checkCode = redisUtil.get(sysLoginModel.getCheckKey());
if(checkCode==null) {
result.error500("验证码失效");
return result;
}
if(!checkCode.equals(sysLoginModel.getCaptcha())) {
result.error500("验证码错误");
return result;
}
//update-end-author:taoyan date:20190828 for:校验验证码
//1. 校验用户是否有效
SysUser sysUser = sysUserService.getUserByName(username);
result = sysUserService.checkUserIsEffective(sysUser);
@ -112,18 +110,17 @@ public class LoginController {
return Result.error("退出登录失败!");
}
String username = JwtUtil.getUsername(token);
SysUser sysUser = sysUserService.getUserByName(username);
LoginUser sysUser = sysBaseAPI.getUserByName(username);
if(sysUser!=null) {
sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功!", CommonConstant.LOG_TYPE_1, null);
log.info(" 用户名: "+sysUser.getRealname()+",退出成功! ");
//清空用户Token缓存
//清空用户登录Token缓存
redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
//清空用户权限缓存权限Perms和角色集合
redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_ROLE + username);
redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + username);
//清空用户登录Shiro权限缓存
redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
return Result.ok("退出登录成功!");
}else {
return Result.error("无效的token");
return Result.error("Token无效!");
}
}
@ -283,6 +280,7 @@ public class LoginController {
* @param jsonObject
* @return
*/
@ApiOperation("手机号登录接口")
@PostMapping("/phoneLogin")
public Result<JSONObject> phoneLogin(@RequestBody JSONObject jsonObject) {
Result<JSONObject> result = new Result<JSONObject>();
@ -322,9 +320,9 @@ public class LoginController {
String username = sysUser.getUsername();
// 生成token
String token = JwtUtil.sign(username, syspassword);
// 设置token缓存有效时间
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
// 设置超时时间
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
// 获取用户部门信息
JSONObject obj = new JSONObject();
@ -358,5 +356,85 @@ public class LoginController {
result.setResult(map);
return result;
}
/**
* 获取校验码
*/
@ApiOperation("获取验证码")
@GetMapping(value = "/getCheckCode")
public Result<Map<String,String>> getCheckCode(){
Result<Map<String,String>> result = new Result<Map<String,String>>();
Map<String,String> map = new HashMap<String,String>();
try {
String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
String key = MD5Util.MD5Encode(code+System.currentTimeMillis(), "utf-8");
redisUtil.set(key, code, 60);
map.put("key", key);
map.put("code",code);
result.setResult(map);
result.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
}
return result;
}
/**
* app登录
* @param sysLoginModel
* @return
* @throws Exception
*/
@RequestMapping(value = "/mLogin", method = RequestMethod.POST)
public Result<JSONObject> mLogin(@RequestBody SysLoginModel sysLoginModel) throws Exception {
Result<JSONObject> result = new Result<JSONObject>();
String username = sysLoginModel.getUsername();
String password = sysLoginModel.getPassword();
//1. 校验用户是否有效
SysUser sysUser = sysUserService.getUserByName(username);
result = sysUserService.checkUserIsEffective(sysUser);
if(!result.isSuccess()) {
return result;
}
//2. 校验用户名或密码是否正确
String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
String syspassword = sysUser.getPassword();
if (!syspassword.equals(userpassword)) {
result.error500("用户名或密码错误");
return result;
}
String orgCode = sysUser.getOrgCode();
if(oConvertUtils.isEmpty(orgCode)) {
//如果当前用户无选择部门 查看部门关联信息
List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
if (departs == null || departs.size() == 0) {
result.error500("用户暂未归属部门,不可登录!");
return result;
}
orgCode = departs.get(0).getOrgCode();
sysUser.setOrgCode(orgCode);
this.sysUserService.updateUserDepart(username, orgCode);
}
JSONObject obj = new JSONObject();
//用户登录信息
obj.put("userInfo", sysUser);
// 生成token
String token = JwtUtil.sign(username, syspassword);
// 设置超时时间
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
//token 信息
obj.put("token", token);
result.setResult(obj);
result.setSuccess(true);
result.setCode(200);
sysBaseAPI.addLog("用户名: " + username + ",登录成功[移动端]", CommonConstant.LOG_TYPE_1, null);
return result;
}
}

View File

@ -101,7 +101,7 @@ public class SysAnnouncementController {
result.setResult(pageList);
return result;
}
/**
* 添加
* @param sysAnnouncement
@ -121,7 +121,7 @@ public class SysAnnouncementController {
}
return result;
}
/**
* 编辑
* @param sysAnnouncement
@ -140,10 +140,10 @@ public class SysAnnouncementController {
result.success("修改成功!");
}
}
return result;
}
/**
* 通过id删除
* @param id
@ -162,10 +162,10 @@ public class SysAnnouncementController {
result.success("删除成功!");
}
}
return result;
}
/**
* 批量删除
* @param ids
@ -187,7 +187,7 @@ public class SysAnnouncementController {
}
return result;
}
/**
* 通过id查询
* @param id
@ -205,7 +205,7 @@ public class SysAnnouncementController {
}
return result;
}
/**
* 更新发布操作
* @param id
@ -245,10 +245,10 @@ public class SysAnnouncementController {
}
}
}
return result;
}
/**
* 更新撤销操作
* @param id
@ -268,10 +268,10 @@ public class SysAnnouncementController {
result.success("该系统通知撤销成功");
}
}
return result;
}
/**
* @功能:补充用户数据,并返回系统消息
* @param id
@ -288,6 +288,7 @@ public class SysAnnouncementController {
querySaWrapper.eq(SysAnnouncement::getMsgType,CommonConstant.MSG_TYPE_ALL); // 全部人员
querySaWrapper.eq(SysAnnouncement::getDelFlag,CommonConstant.DEL_FLAG_0.toString()); // 未删除
querySaWrapper.eq(SysAnnouncement::getSendStatus, CommonConstant.HAS_SEND); //已发布
querySaWrapper.ge(SysAnnouncement::getEndTime, sysUser.getCreateTime()); //新注册用户不看结束通知
if(anntIds!=null&&anntIds.size()>0) {
querySaWrapper.notIn(SysAnnouncement::getId, anntIds);
}
@ -321,7 +322,6 @@ public class SysAnnouncementController {
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(SysAnnouncement sysAnnouncement,HttpServletRequest request) {

View File

@ -1,6 +1,7 @@
package org.jeecg.modules.system.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@ -9,9 +10,12 @@ import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysCategory;
@ -23,15 +27,7 @@ import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@ -339,4 +335,122 @@ public class SysCategoryController {
}
}
/**
* 校验编码
* @param pid
* @param code
* @return
*/
@GetMapping(value = "/checkCode")
public Result<?> checkCode(@RequestParam(name="pid",required = false) String pid,@RequestParam(name="code",required = false) String code) {
if(oConvertUtils.isEmpty(code)){
return Result.error("错误,类型编码为空!");
}
if(oConvertUtils.isEmpty(pid)){
return Result.ok();
}
SysCategory parent = this.sysCategoryService.getById(pid);
if(code.startsWith(parent.getCode())){
return Result.ok();
}else{
return Result.error("编码不符合规范,须以\""+parent.getCode()+"\"开头!");
}
}
/**
* 分类字典树控件 加载节点
* @param pid
* @param pcode
* @param condition
* @return
*/
@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
public Result<List<TreeSelectModel>> loadDict(@RequestParam(name="pid",required = false) String pid,@RequestParam(name="pcode",required = false) String pcode, @RequestParam(name="condition",required = false) String condition) {
Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
//pid如果传值了 就忽略pcode的作用
if(oConvertUtils.isEmpty(pid)){
if(oConvertUtils.isEmpty(pcode)){
result.setSuccess(false);
result.setMessage("加载分类字典树参数有误.[null]!");
return result;
}else{
if(sysCategoryService.ROOT_PID_VALUE.equals(pcode)){
pid = sysCategoryService.ROOT_PID_VALUE;
}else{
pid = this.sysCategoryService.queryIdByCode(pcode);
}
if(oConvertUtils.isEmpty(pid)){
result.setSuccess(false);
result.setMessage("加载分类字典树参数有误.[code]!");
return result;
}
}
}
Map<String, String> query = null;
if(oConvertUtils.isNotEmpty(condition)) {
query = JSON.parseObject(condition, Map.class);
}
List<TreeSelectModel> ls = sysCategoryService.queryListByPid(pid,query);
result.setSuccess(true);
result.setResult(ls);
return result;
}
/**
* 分类字典控件数据回显[表单页面]
* @param key
* @return
*/
@RequestMapping(value = "/loadDictItem", method = RequestMethod.GET)
public Result<List<String>> loadDictItem(@RequestParam(name="ids") String ids) {
Result<List<String>> result = new Result<>();
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>().in(SysCategory::getId,ids);
List<SysCategory> list = this.sysCategoryService.list(query);
List<String> textList = new ArrayList<String>();
for (String id : ids.split(",")) {
for (SysCategory c : list) {
if(id.equals(c.getId())){
textList.add(c.getName());
break;
}
}
}
result.setSuccess(true);
result.setResult(textList);
return result;
}
/**
* [列表页面]加载分类字典数据 用于值的替换
* @param code
* @return
*/
@RequestMapping(value = "/loadAllData", method = RequestMethod.GET)
public Result<List<DictModel>> loadAllData(@RequestParam(name="code",required = true) String code) {
Result<List<DictModel>> result = new Result<List<DictModel>>();
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>();
if(oConvertUtils.isNotEmpty(code) && !"0".equals(code)){
query.likeRight(SysCategory::getCode,code);
}
List<SysCategory> list = this.sysCategoryService.list(query);
if(list==null || list.size()==0) {
result.setMessage("无数据,参数有误.[code]");
result.setSuccess(false);
return result;
}
List<DictModel> rdList = new ArrayList<DictModel>();
for (SysCategory c : list) {
rdList.add(new DictModel(c.getId(),c.getName()));
}
result.setSuccess(true);
result.setResult(rdList);
return result;
}
}

View File

@ -88,7 +88,7 @@ public class SysDepartController {
* @return
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.DEPART_INFO_CACHE,CacheConstant.DEPART_IDMODEL_CACHE}, allEntries=true)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
Result<SysDepart> result = new Result<SysDepart>();
String username = JwtUtil.getUserNameByToken(request);
@ -113,7 +113,7 @@ public class SysDepartController {
* @return
*/
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value= {CacheConstant.DEPART_INFO_CACHE,CacheConstant.DEPART_IDMODEL_CACHE}, allEntries=true)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
String username = JwtUtil.getUserNameByToken(request);
sysDepart.setUpdateBy(username);
@ -140,7 +140,7 @@ public class SysDepartController {
* @return
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
@CacheEvict(value= {CacheConstant.DEPART_INFO_CACHE,CacheConstant.DEPART_IDMODEL_CACHE}, allEntries=true)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> delete(@RequestParam(name="id",required=true) String id) {
Result<SysDepart> result = new Result<SysDepart>();
@ -167,7 +167,7 @@ public class SysDepartController {
* @return
*/
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
@CacheEvict(value= {CacheConstant.DEPART_INFO_CACHE,CacheConstant.DEPART_IDMODEL_CACHE}, allEntries=true)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<SysDepart> result = new Result<SysDepart>();
@ -282,6 +282,7 @@ public class SysDepartController {
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

View File

@ -10,6 +10,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
@ -44,6 +45,8 @@ import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
@ -237,7 +240,7 @@ public class SysDictController {
* @return
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
@CacheEvict(value=CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value=CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDict> delete(@RequestParam(name="id",required=true) String id) {
Result<SysDict> result = new Result<SysDict>();
boolean ok = sysDictService.removeById(id);
@ -255,7 +258,7 @@ public class SysDictController {
* @return
*/
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
@CacheEvict(value= CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value= CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDict> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
Result<SysDict> result = new Result<SysDict>();
if(oConvertUtils.isEmpty(ids)) {
@ -382,8 +385,8 @@ public class SysDictController {
* 根据字典code加载字典text 返回
*/
@RequestMapping(value = "/loadDictItem/{dictCode}", method = RequestMethod.GET)
public Result<String> loadDictItem(@PathVariable String dictCode,@RequestParam(name="key") String key) {
Result<String> result = new Result<String>();
public Result<List<String>> loadDictItem(@PathVariable String dictCode,@RequestParam(name="key") String key) {
Result<List<String>> result = new Result<>();
try {
if(dictCode.indexOf(",")!=-1) {
String[] params = dictCode.split(",");
@ -391,9 +394,10 @@ public class SysDictController {
result.error500("字典Code格式不正确");
return result;
}
String text = sysDictService.queryTableDictTextByKey(params[0], params[1], params[2], key);
List<String> texts = sysDictService.queryTableDictByKeys(params[0], params[1], params[2], key.split(","));
result.setSuccess(true);
result.setResult(text);
result.setResult(texts);
log.info(result.toString());
}else {
result.error500("字典Code格式不正确");
@ -410,17 +414,69 @@ public class SysDictController {
/**
* 根据表名——显示字段-存储字段 pid 加载树形数据
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
public Result<List<TreeSelectModel>> loadDict(@RequestParam(name="pid") String pid,@RequestParam(name="pidField") String pidField,
@RequestParam(name="tableName") String tbname,
@RequestParam(name="text") String text,
@RequestParam(name="code") String code,
@RequestParam(name="hasChildField") String hasChildField) {
@RequestParam(name="hasChildField") String hasChildField,
@RequestParam(name="condition") String condition) {
Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
List<TreeSelectModel> ls = sysDictService.queryTreeList(tbname, text, code, pidField, pid,hasChildField);
Map<String, String> query = null;
if(oConvertUtils.isNotEmpty(condition)) {
query = JSON.parseObject(condition, Map.class);
}
List<TreeSelectModel> ls = sysDictService.queryTreeList(query,tbname, text, code, pidField, pid,hasChildField);
result.setSuccess(true);
result.setResult(ls);
return result;
}
/**
* 查询被删除的列表
* @return
*/
@RequestMapping(value = "/deleteList", method = RequestMethod.GET)
public Result<List<SysDict>> deleteList() {
Result<List<SysDict>> result = new Result<List<SysDict>>();
List<SysDict> list = this.sysDictService.queryDeleteList();
result.setSuccess(true);
result.setResult(list);
return result;
}
/**
* 物理删除
* @param id
* @return
*/
@RequestMapping(value = "/deletePhysic/{id}", method = RequestMethod.DELETE)
public Result<?> deletePhysic(@PathVariable String id) {
try {
sysDictService.deleteOneDictPhysically(id);
return Result.ok("删除成功!");
} catch (Exception e) {
e.printStackTrace();
return Result.error("删除失败!");
}
}
/**
* 取回
* @param id
* @return
*/
@RequestMapping(value = "/back/{id}", method = RequestMethod.PUT)
public Result<?> back(@PathVariable String id) {
try {
sysDictService.updateDictDelFlag(0,id);
return Result.ok("操作成功!");
} catch (Exception e) {
e.printStackTrace();
return Result.error("操作失败!");
}
}
}

View File

@ -69,7 +69,7 @@ public class SysDictItemController {
* @return
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value= CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDictItem> add(@RequestBody SysDictItem sysDictItem) {
Result<SysDictItem> result = new Result<SysDictItem>();
try {
@ -89,7 +89,7 @@ public class SysDictItemController {
* @return
*/
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value=CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value=CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDictItem> edit(@RequestBody SysDictItem sysDictItem) {
Result<SysDictItem> result = new Result<SysDictItem>();
SysDictItem sysdict = sysDictItemService.getById(sysDictItem.getId());
@ -112,7 +112,7 @@ public class SysDictItemController {
* @return
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
@CacheEvict(value=CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value=CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDictItem> delete(@RequestParam(name="id",required=true) String id) {
Result<SysDictItem> result = new Result<SysDictItem>();
SysDictItem joinSystem = sysDictItemService.getById(id);
@ -133,7 +133,7 @@ public class SysDictItemController {
* @return
*/
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
@CacheEvict(value=CacheConstant.DICT_CACHE, allEntries=true)
@CacheEvict(value=CacheConstant.SYS_DICT_CACHE, allEntries=true)
public Result<SysDictItem> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
Result<SysDictItem> result = new Result<SysDictItem>();
if(ids==null || "".equals(ids.trim())) {

View File

@ -25,6 +25,7 @@ import org.jeecg.modules.system.service.ISysRolePermissionService;
import org.jeecg.modules.system.util.PermissionDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@ -67,6 +68,7 @@ public class SysPermissionController {
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public Result<List<SysPermissionTree>> list() {
long start = System.currentTimeMillis();
Result<List<SysPermissionTree>> result = new Result<>();
try {
LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
@ -77,12 +79,72 @@ public class SysPermissionController {
getTreeList(treeList, list, null);
result.setResult(treeList);
result.setSuccess(true);
log.info("======获取全部菜单数据=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
/*update_begin author:wuxianquan date:20190908 for:先查询一级菜单,当用户点击展开菜单时加载子菜单 */
/**
* 系统菜单列表(一级菜单)
*
* @return
*/
@RequestMapping(value = "/getSystemMenuList", method = RequestMethod.GET)
public Result<List<SysPermissionTree>> getSystemMenuList() {
long start = System.currentTimeMillis();
Result<List<SysPermissionTree>> result = new Result<>();
try {
LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
query.eq(SysPermission::getMenuType,CommonConstant.MENU_TYPE_0);
query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
query.orderByAsc(SysPermission::getSortNo);
List<SysPermission> list = sysPermissionService.list(query);
List<SysPermissionTree> sysPermissionTreeList = new ArrayList<SysPermissionTree>();
for(SysPermission sysPermission : list){
SysPermissionTree sysPermissionTree = new SysPermissionTree(sysPermission);
sysPermissionTreeList.add(sysPermissionTree);
}
result.setResult(sysPermissionTreeList);
result.setSuccess(true);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("======获取一级菜单数据=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
return result;
}
/**
* 查询子菜单
* @param parentId
* @return
*/
@RequestMapping(value = "/getSystemSubmenu", method = RequestMethod.GET)
public Result<List<SysPermissionTree>> getSystemSubmenu(@RequestParam("parentId") String parentId){
Result<List<SysPermissionTree>> result = new Result<>();
try{
LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
query.eq(SysPermission::getParentId,parentId);
query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
query.orderByAsc(SysPermission::getSortNo);
List<SysPermission> list = sysPermissionService.list(query);
List<SysPermissionTree> sysPermissionTreeList = new ArrayList<SysPermissionTree>();
for(SysPermission sysPermission : list){
SysPermissionTree sysPermissionTree = new SysPermissionTree(sysPermission);
sysPermissionTreeList.add(sysPermissionTree);
}
result.setResult(sysPermissionTreeList);
result.setSuccess(true);
}catch (Exception e){
log.error(e.getMessage(), e);
}
return result;
}
/*update_end author:wuxianquan date:20190908 for:先查询一级菜单,当用户点击展开菜单时加载子菜单 */
// /**
// * 查询用户拥有的菜单权限和按钮权限(根据用户账号)
// *
@ -172,7 +234,6 @@ public class SysPermissionController {
* @return
*/
@RequiresRoles({ "admin" })
@CacheEvict(value= CacheConstant.LOGIN_USER_RULES_CACHE, allEntries=true)
@RequestMapping(value = "/edit", method = { RequestMethod.PUT, RequestMethod.POST })
public Result<SysPermission> edit(@RequestBody SysPermission permission) {
Result<SysPermission> result = new Result<>();
@ -193,7 +254,6 @@ public class SysPermissionController {
* @return
*/
@RequiresRoles({ "admin" })
@CacheEvict(value=CacheConstant.LOGIN_USER_RULES_CACHE, allEntries=true)
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result<SysPermission> delete(@RequestParam(name = "id", required = true) String id) {
Result<SysPermission> result = new Result<>();
@ -214,7 +274,6 @@ public class SysPermissionController {
* @return
*/
@RequiresRoles({ "admin" })
@CacheEvict(value=CacheConstant.LOGIN_USER_RULES_CACHE, allEntries=true)
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
public Result<SysPermission> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<SysPermission> result = new Result<>();
@ -504,6 +563,15 @@ public class SysPermissionController {
meta.put("keepAlive", false);
}
/*update_begin author:wuxianquan date:20190908 for:往菜单信息里添加外链菜单打开方式 */
//外链菜单打开方式
if (permission.isInternalOrExternal()) {
meta.put("internalOrExternal", true);
} else {
meta.put("internalOrExternal", false);
}
/* update_end author:wuxianquan date:20190908 for: 往菜单信息里添加外链菜单打开方式*/
meta.put("title", permission.getName());
if (oConvertUtils.isEmpty(permission.getParentId())) {
// 一级菜单跳转地址

View File

@ -0,0 +1,249 @@
package org.jeecg.modules.system.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysPosition;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @Description: 职务表
* @Author: jeecg-boot
* @Date: 2019-09-19
* @Version: V1.0
*/
@Slf4j
@Api(tags = "职务表")
@RestController
@RequestMapping("/sys/position")
public class SysPositionController {
@Autowired
private ISysPositionService sysPositionService;
/**
* 分页列表查询
*
* @param sysPosition
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@AutoLog(value = "职务表-分页列表查询")
@ApiOperation(value = "职务表-分页列表查询", notes = "职务表-分页列表查询")
@GetMapping(value = "/list")
public Result<IPage<SysPosition>> queryPageList(SysPosition sysPosition,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
Result<IPage<SysPosition>> result = new Result<IPage<SysPosition>>();
QueryWrapper<SysPosition> queryWrapper = QueryGenerator.initQueryWrapper(sysPosition, req.getParameterMap());
Page<SysPosition> page = new Page<SysPosition>(pageNo, pageSize);
IPage<SysPosition> pageList = sysPositionService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
}
/**
* 添加
*
* @param sysPosition
* @return
*/
@AutoLog(value = "职务表-添加")
@ApiOperation(value = "职务表-添加", notes = "职务表-添加")
@PostMapping(value = "/add")
public Result<SysPosition> add(@RequestBody SysPosition sysPosition) {
Result<SysPosition> result = new Result<SysPosition>();
try {
sysPositionService.save(sysPosition);
result.success("添加成功!");
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("操作失败");
}
return result;
}
/**
* 编辑
*
* @param sysPosition
* @return
*/
@AutoLog(value = "职务表-编辑")
@ApiOperation(value = "职务表-编辑", notes = "职务表-编辑")
@PutMapping(value = "/edit")
public Result<SysPosition> edit(@RequestBody SysPosition sysPosition) {
Result<SysPosition> result = new Result<SysPosition>();
SysPosition sysPositionEntity = sysPositionService.getById(sysPosition.getId());
if (sysPositionEntity == null) {
result.error500("未找到对应实体");
} else {
boolean ok = sysPositionService.updateById(sysPosition);
//TODO 返回false说明什么
if (ok) {
result.success("修改成功!");
}
}
return result;
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "职务表-通过id删除")
@ApiOperation(value = "职务表-通过id删除", notes = "职务表-通过id删除")
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
try {
sysPositionService.removeById(id);
} catch (Exception e) {
log.error("删除失败", e.getMessage());
return Result.error("删除失败!");
}
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "职务表-批量删除")
@ApiOperation(value = "职务表-批量删除", notes = "职务表-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<SysPosition> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
Result<SysPosition> result = new Result<SysPosition>();
if (ids == null || "".equals(ids.trim())) {
result.error500("参数不识别!");
} else {
this.sysPositionService.removeByIds(Arrays.asList(ids.split(",")));
result.success("删除成功!");
}
return result;
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "职务表-通过id查询")
@ApiOperation(value = "职务表-通过id查询", notes = "职务表-通过id查询")
@GetMapping(value = "/queryById")
public Result<SysPosition> queryById(@RequestParam(name = "id", required = true) String id) {
Result<SysPosition> result = new Result<SysPosition>();
SysPosition sysPosition = sysPositionService.getById(id);
if (sysPosition == null) {
result.error500("未找到对应实体");
} else {
result.setResult(sysPosition);
result.setSuccess(true);
}
return result;
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
// Step.1 组装查询条件
QueryWrapper<SysPosition> queryWrapper = null;
try {
String paramsStr = request.getParameter("paramsStr");
if (oConvertUtils.isNotEmpty(paramsStr)) {
String deString = URLDecoder.decode(paramsStr, "UTF-8");
SysPosition sysPosition = JSON.parseObject(deString, SysPosition.class);
queryWrapper = QueryGenerator.initQueryWrapper(sysPosition, request.getParameterMap());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<SysPosition> pageList = sysPositionService.list(queryWrapper);
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "职务表列表");
mv.addObject(NormalExcelConstants.CLASS, SysPosition.class);
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("职务表列表数据", "导出人:Jeecg", "导出信息"));
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<SysPosition> listSysPositions = ExcelImportUtil.importExcel(file.getInputStream(), SysPosition.class, params);
sysPositionService.saveBatch(listSysPositions);
return Result.ok("文件导入成功!数据行数:" + listSysPositions.size());
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("文件导入失败:" + e.getMessage());
} finally {
try {
file.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Result.ok("文件导入失败!");
}
}

View File

@ -1,6 +1,7 @@
package org.jeecg.modules.system.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@ -17,6 +18,7 @@ import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PmsUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.entity.SysPermissionDataRule;
@ -148,7 +150,6 @@ public class SysRoleController {
* @param id
* @return
*/
@CacheEvict(value= CacheConstant.LOGIN_USER_RULES_CACHE, allEntries=true)
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result<SysRole> delete(@RequestParam(name="id",required=true) String id) {
Result<SysRole> result = new Result<SysRole>();
@ -170,7 +171,6 @@ public class SysRoleController {
* @param ids
* @return
*/
@CacheEvict(value=CacheConstant.LOGIN_USER_RULES_CACHE, allEntries=true)
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
public Result<SysRole> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
Result<SysRole> result = new Result<SysRole>();
@ -290,14 +290,10 @@ public class SysRoleController {
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<SysRole> listSysRoles = ExcelImportUtil.importExcel(file.getInputStream(), SysRole.class, params);
for (SysRole sysRoleExcel : listSysRoles) {
sysRoleService.save(sysRoleExcel);
}
return Result.ok("文件导入成功!数据行数:" + listSysRoles.size());
return sysRoleService.importExcelCheckRoleCode(file, params);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("文件导入失败:"+e.getMessage());
return Result.error("文件导入失败:" + e.getMessage());
} finally {
try {
file.getInputStream().close();
@ -358,7 +354,7 @@ public class SysRoleController {
this.sysRolePermissionService.updateById(sysRolePermission);
}
} catch (Exception e) {
log.error("SysRoleController.saveDatarule()发生异常:" + e.getMessage());
log.error("SysRoleController.saveDatarule()发生异常:" + e.getMessage(),e);
return Result.error("保存失败");
}
return Result.ok("保存成功!");

View File

@ -14,10 +14,13 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
@ -26,11 +29,9 @@ import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
@ -43,6 +44,7 @@ import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@ -110,7 +112,7 @@ public class SysUserController {
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@RequiresPermissions("user:add")
@RequiresPermissions("user:add")
public Result<SysUser> add(@RequestBody JSONObject jsonObject) {
Result<SysUser> result = new Result<SysUser>();
String selectedRoles = jsonObject.getString("selectedroles");
@ -165,49 +167,20 @@ public class SysUserController {
* 删除用户
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result<SysUser> delete(@RequestParam(name="id",required=true) String id) {
Result<SysUser> result = new Result<SysUser>();
// 定义SysUserDepart实体类的数据库查询LambdaQueryWrapper
LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<SysUserDepart>();
SysUser sysUser = sysUserService.getById(id);
public Result<?> delete(@RequestParam(name="id",required=true) String id) {
sysBaseAPI.addLog("删除用户id " +id ,CommonConstant.LOG_TYPE_2, 3);
if(sysUser==null) {
result.error500("未找到对应实体");
}else {
// 当某个用户被删除时,删除其ID下对应的部门数据
query.eq(SysUserDepart::getUserId, id);
boolean ok = sysUserService.removeById(id);
sysUserDepartService.remove(query);
if(ok) {
result.success("删除成功!");
}
}
return result;
this.sysUserService.deleteUser(id);
return Result.ok("删除用户成功");
}
/**
* 批量删除用户
*/
@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
public Result<SysUser> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
// 定义SysUserDepart实体类的数据库查询对象LambdaQueryWrapper
LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<SysUserDepart>();
String[] idArry = ids.split(",");
sysBaseAPI.addLog("批量删除用户, id " +idArry.toString() ,CommonConstant.LOG_TYPE_2, 3);
Result<SysUser> result = new Result<SysUser>();
if(ids==null || "".equals(ids.trim())) {
result.error500("参数不识别!");
}else {
this.sysUserService.removeByIds(Arrays.asList(ids.split(",")));
// 当批量删除时,删除在SysUserDepart中对应的所有部门数据
for(String id : idArry) {
query.eq(SysUserDepart::getUserId, id);
this.sysUserDepartService.remove(query);
}
result.success("删除成功!");
}
return result;
public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
sysBaseAPI.addLog("批量删除用户, ids " +ids ,CommonConstant.LOG_TYPE_2, 3);
this.sysUserService.deleteBatchUsers(ids);
return Result.ok("批量删除用户成功");
}
/**
@ -302,22 +275,13 @@ public class SysUserController {
* 修改密码
*/
@RequestMapping(value = "/changPassword", method = RequestMethod.PUT)
public Result<SysUser> changPassword(@RequestBody SysUser sysUser) {
Result<SysUser> result = new Result<SysUser>();
String password = sysUser.getPassword();
sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
if (sysUser == null) {
result.error500("未找到对应实体");
} else {
String salt = oConvertUtils.randomGen(8);
sysUser.setSalt(salt);
String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
sysUser.setPassword(passwordEncode);
this.sysUserService.updateById(sysUser);
result.setResult(sysUser);
result.success("密码修改完成!");
public Result<?> changPassword(@RequestBody SysUser sysUser) {
SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
if (u == null) {
return Result.error("用户不存在!");
}
return result;
sysUser.setId(u.getId());
return sysUserService.changePassword(sysUser);
}
/**
@ -411,7 +375,14 @@ public class SysUserController {
QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//update-begin--Author:kangxiaolin Date:20180825 for[03]用户导出,如果选择数据则只导出相关数据--------------------
String selections = request.getParameter("selections");
if(!oConvertUtils.isEmpty(selections)){
queryWrapper.in("id",selections.split(","));
}
//update-end--Author:kangxiaolin Date:20180825 for[03]用户导出,如果选择数据则只导出相关数据----------------------
List<SysUser> pageList = sysUserService.list(queryWrapper);
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
@ -480,39 +451,19 @@ public class SysUserController {
}
/**
* 首页密码修改
* 首页用户重置密码
*/
@RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
public Result<SysUser> changPassword(@RequestBody JSONObject json) {
Result<SysUser> result = new Result<SysUser>();
public Result<?> changPassword(@RequestBody JSONObject json) {
String username = json.getString("username");
String oldpassword = json.getString("oldpassword");
SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
if(user==null) {
result.error500("未找到用户!");
return result;
}
String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
if(!user.getPassword().equals(passwordEncode)) {
result.error500("旧密码输入错误!");
return result;
}
String password = json.getString("password");
String confirmpassword = json.getString("confirmpassword");
if(oConvertUtils.isEmpty(password)) {
result.error500("新密码不存在!");
return result;
SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
if(user==null) {
return Result.error("用户不存在!");
}
if(!password.equals(confirmpassword)) {
result.error500("两次输入密码不一致!");
return result;
}
String newpassword = PasswordUtil.encrypt(username, password, user.getSalt());
this.sysUserService.update(new SysUser().setPassword(newpassword), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
result.success("密码修改完成!");
return result;
return sysUserService.resetPassword(username,oldpassword,password,confirmpassword);
}
@RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
@ -620,6 +571,68 @@ public class SysUserController {
return result;
}
/**
* 根据 orgCode 查询用户,包括子部门下的用户
* 若某个用户包含多个部门,则会显示多条记录,可自行处理成单条记录
*/
@GetMapping("/queryByOrgCode")
public Result<?> queryByDepartId(
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
@RequestParam(name = "orgCode") String orgCode,
SysUser userParams
) {
IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, new Page(pageNo, pageSize));
return Result.ok(pageList);
}
/**
* 根据 orgCode 查询用户,包括子部门下的用户
* 针对通讯录模块做的接口,将多个部门的用户合并成一条记录,并转成对前端友好的格式
*/
@GetMapping("/queryByOrgCodeForAddressList")
public Result<?> queryByOrgCodeForAddressList(
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
@RequestParam(name = "orgCode") String orgCode,
SysUser userParams
) {
IPage page = new Page(pageNo, pageSize);
IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
List<SysUserSysDepartModel> list = pageList.getRecords();
// 记录所有出现过的 user, key = userId
Map<String, JSONObject> hasUser = new HashMap<>(list.size());
JSONArray resultJson = new JSONArray(list.size());
for (SysUserSysDepartModel item : list) {
String userId = item.getSysUser().getId();
// userId
JSONObject getModel = hasUser.get(userId);
// 之前已存在过该用户,直接合并数据
if (getModel != null) {
String departName = getModel.get("departName").toString();
getModel.put("departName", (departName + " | " + item.getSysDepart().getDepartName()));
} else {
// 将用户对象转换为json格式并将部门信息合并到 json 中
JSONObject json = JSON.parseObject(JSON.toJSONString(item.getSysUser()));
json.remove("id");
json.put("userId", userId);
json.put("departId", item.getSysDepart().getId());
json.put("departName", item.getSysDepart().getDepartName());
resultJson.add(json);
hasUser.put(userId, json);
}
}
IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
result.setRecords(resultJson.toJavaList(JSONObject.class));
return Result.ok(result);
}
/**
* 给指定部门添加对应的用户
*/
@ -904,4 +917,32 @@ public class SysUserController {
}
}
/**
* 获取用户列表 根据用户名和真实名 模糊匹配
* @param keyword
* @param pageNo
* @param pageSize
* @return
*/
@GetMapping("/appUserList")
public Result<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
try {
//TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>();
query.eq(SysUser::getActivitiSync, "1");
query.eq(SysUser::getDelFlag,"0");
query.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
Page<SysUser> page = new Page<>(pageNo, pageSize);
IPage<SysUser> res = this.sysUserService.page(page, query);
return Result.ok(res);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error(500, "查询失败:" + e.getMessage());
}
}
}

View File

@ -26,7 +26,7 @@ public class SysAnnouncement implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**
* 标题

View File

@ -21,7 +21,7 @@ public class SysAnnouncementSend implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**通告id*/
private java.lang.String anntId;

View File

@ -24,7 +24,7 @@ public class SysCategory implements Serializable {
private static final long serialVersionUID = 1L;
/**主键*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**父级节点*/
@Excel(name = "父级节点", width = 15)

View File

@ -19,7 +19,7 @@ import lombok.experimental.Accessors;
public class SysDataLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id; //id'
private String createBy; //创建人登录名称
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")

View File

@ -29,7 +29,7 @@ public class SysDepart implements Serializable {
private static final long serialVersionUID = 1L;
/**ID*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**父机构ID*/
private String parentId;
@ -47,6 +47,9 @@ public class SysDepart implements Serializable {
/**描述*/
@Excel(name="描述",width=15)
private Object description;
/**机构类别 1组织机构2岗位*/
@Excel(name="机构类别",width=15)
private String orgCategory;
/**机构类型*/
@Excel(name="机构类型",width=15)
private String orgType;
@ -108,6 +111,7 @@ public class SysDepart implements Serializable {
Objects.equals(departNameAbbr, depart.departNameAbbr) &&
Objects.equals(departOrder, depart.departOrder) &&
Objects.equals(description, depart.description) &&
Objects.equals(orgCategory, depart.orgCategory) &&
Objects.equals(orgType, depart.orgType) &&
Objects.equals(orgCode, depart.orgCode) &&
Objects.equals(mobile, depart.mobile) &&
@ -129,7 +133,7 @@ public class SysDepart implements Serializable {
public int hashCode() {
return Objects.hash(super.hashCode(), id, parentId, departName,
departNameEn, departNameAbbr, departOrder, description,
departNameEn, departNameAbbr, departOrder, description,orgCategory,
orgType, orgCode, mobile, fax, address, memo, status,
delFlag, createBy, createTime, updateBy, updateTime);
}

View File

@ -29,7 +29,7 @@ public class SysDict implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -31,7 +31,7 @@ public class SysDictItem implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -30,7 +30,7 @@ public class SysLog implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -29,7 +29,7 @@ public class SysPermission implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**
@ -78,7 +78,7 @@ public class SysPermission implements Serializable {
/**
* 菜单排序
*/
private Integer sortNo;
private Double sortNo;
/**
* 类型0一级菜单1子菜单 2按钮权限
@ -150,7 +150,12 @@ public class SysPermission implements Serializable {
/**alwaysShow*/
private boolean alwaysShow;
/*update_begin author:wuxianquan date:20190908 for:实体增加字段 */
/** 外链菜单打开方式 0/内部打开 1/外部打开 */
private boolean internalOrExternal;
/*update_end author:wuxianquan date:20190908 for:实体增加字段 */
public SysPermission() {
}
@ -162,7 +167,7 @@ public class SysPermission implements Serializable {
this.url="/dashboard/analysis";
this.icon="home";
this.menuType=0;
this.sortNo=0;
this.sortNo=0.0;
this.ruleFlag=0;
this.delFlag=0;
this.alwaysShow=false;

View File

@ -28,7 +28,7 @@ public class SysPermissionDataRule implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -0,0 +1,94 @@
package org.jeecg.modules.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat;
/**
* @Description: 职务表
* @Author: jeecg-boot
* @Date: 2019-09-19
* @Version: V1.0
*/
@Data
@TableName("sys_position")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value = "sys_position对象", description = "职务表")
public class SysPosition {
/**
* id
*/
@TableId(type = IdType.ID_WORKER_STR)
@ApiModelProperty(value = "id")
private java.lang.String id;
/**
* 职务编码
*/
@Excel(name = "职务编码", width = 15)
@ApiModelProperty(value = "职务编码")
private java.lang.String code;
/**
* 职务名称
*/
@Excel(name = "职务名称", width = 15)
@ApiModelProperty(value = "职务名称")
private java.lang.String name;
/**
* 职级
*/
@Excel(name = "职级", width = 15)
@ApiModelProperty(value = "职级")
@Dict(dicCode = "position_rank")
private java.lang.String rank;
/**
* 公司id
*/
@Excel(name = "公司id", width = 15)
@ApiModelProperty(value = "公司id")
private java.lang.String companyId;
/**
* 创建人
*/
@Excel(name = "创建人", width = 15)
@ApiModelProperty(value = "创建人")
private java.lang.String createBy;
/**
* 创建时间
*/
@Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
private java.util.Date createTime;
/**
* 修改人
*/
@Excel(name = "修改人", width = 15)
@ApiModelProperty(value = "修改人")
private java.lang.String updateBy;
/**
* 修改时间
*/
@Excel(name = "修改时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "修改时间")
private java.util.Date updateTime;
/**
* 组织机构编码
*/
@Excel(name = "组织机构编码", width = 15)
@ApiModelProperty(value = "组织机构编码")
private java.lang.String sysOrgCode;
}

View File

@ -33,7 +33,7 @@ public class SysRole implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -27,7 +27,7 @@ public class SysRolePermission implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -35,7 +35,7 @@ public class SysUser implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**
@ -112,6 +112,24 @@ public class SysUser implements Serializable {
@TableLogic
private String delFlag;
/**
* 工号,唯一键
*/
@Excel(name = "工号", width = 15)
private String workNo;
/**
* 职务,关联职务表
*/
@Excel(name = "职务", width = 15)
private String post;
/**
* 座机号
*/
@Excel(name = "座机号", width = 15)
private String telephone;
/**
* 创建人
*/

View File

@ -22,7 +22,7 @@ public class SysUserAgent implements Serializable {
private static final long serialVersionUID = 1L;
/**序号*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**用户名*/
@Excel(name = "用户名", width = 15)

View File

@ -13,7 +13,7 @@ public class SysUserDepart implements Serializable {
private static final long serialVersionUID = 1L;
/**主键id*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**用户id*/
private String userId;

View File

@ -24,7 +24,7 @@ public class SysUserRole implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**

View File

@ -1,8 +1,10 @@
package org.jeecg.modules.system.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.model.TreeSelectModel;
@ -21,7 +23,10 @@ public interface SysCategoryMapper extends BaseMapper<SysCategory> {
* @param pid
* @return
*/
public List<TreeSelectModel> queryListByPid(@Param("pid") String pid);
public List<TreeSelectModel> queryListByPid(@Param("pid") String pid,@Param("query") Map<String, String> query);
@Select("SELECT ID FROM sys_category WHERE CODE = #{code,jdbcType=VARCHAR}")
public String queryIdByCode(@Param("code") String code);
}

View File

@ -1,6 +1,7 @@
package org.jeecg.modules.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.TreeModel;
@ -22,4 +23,19 @@ public interface SysDepartMapper extends BaseMapper<SysDepart> {
* 根据用户ID查询部门集合
*/
public List<SysDepart> queryUserDeparts(@Param("userId") String userId);
/**
* 根据用户名查询部门
*
* @param username
* @return
*/
public List<SysDepart> queryDepartsByUsername(@Param("username") String username);
@Select("select id from sys_depart where org_code=#{orgCode}")
public String queryDepartIdByOrgCode(@Param("orgCode") String orgCode);
@Select("select id,parent_id from sys_depart where id=#{departId}")
public SysDepart getParentDepartId(@Param("departId") String departId);
}

View File

@ -1,7 +1,12 @@
package org.jeecg.modules.system.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.model.DuplicateCheckVo;
@ -35,7 +40,8 @@ public interface SysDictMapper extends BaseMapper<SysDict> {
public String queryTableDictTextByKey(@Param("table") String table,@Param("text") String text,@Param("code") String code,@Param("key") String key);
public List<DictModel> queryTableDictByKeys(@Param("table") String table, @Param("text") String text, @Param("code") String code, @Param("keyArray") String[] keyArray);
/**
* 查询所有部门 作为字典信息 id -->value,departName -->text
* @return
@ -67,6 +73,28 @@ public interface SysDictMapper extends BaseMapper<SysDict> {
* @param hasChildField
* @return
*/
List<TreeSelectModel> queryTreeList(@Param("table") String table,@Param("text") String text,@Param("code") String code,@Param("pidField") String pidField,@Param("pid") String pid,@Param("hasChildField") String hasChildField);
List<TreeSelectModel> queryTreeList(@Param("query") Map<String, String> query,@Param("table") String table,@Param("text") String text,@Param("code") String code,@Param("pidField") String pidField,@Param("pid") String pid,@Param("hasChildField") String hasChildField);
/**
* 删除
* @param id
*/
@Select("delete from sys_dict where id = #{id}")
public void deleteOneById(@Param("id") String id);
/**
* 查询被逻辑删除的数据
* @return
*/
@Select("select * from sys_dict where del_flag = 1")
public List<SysDict> queryDeleteList();
/**
* 修改状态值
* @param delFlag
* @param id
*/
@Update("update sys_dict set del_flag = #{flag,jdbcType=INTEGER} where id = #{id,jdbcType=VARCHAR}")
public void updateDictDelFlag(@Param("flag") int delFlag, @Param("id") String id);
}

View File

@ -53,5 +53,5 @@ public interface SysLogMapper extends BaseMapper<SysLog> {
* @param dayEnd
* @return
*/
List<Map<String,Object>> findVisitCount(@Param("dayStart") Date dayStart, @Param("dayEnd") Date dayEnd);
List<Map<String,Object>> findVisitCount(@Param("dayStart") Date dayStart, @Param("dayEnd") Date dayEnd, @Param("dbType") String dbType);
}

View File

@ -0,0 +1,14 @@
package org.jeecg.modules.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.system.entity.SysPosition;
/**
* @Description: 职务表
* @Author: jeecg-boot
* @Date: 2019-09-19
* @Version: V1.0
*/
public interface SysPositionMapper extends BaseMapper<SysPosition> {
}

View File

@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.jeecg.modules.system.entity.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import java.util.List;
/**
* <p>
@ -59,4 +62,25 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
* @return
*/
public SysUser getUserByEmail(@Param("email")String email);
/**
* 根据 orgCode 查询用户,包括子部门下的用户
*
* @param page 分页对象, xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
* @param orgCode
* @param userParams 用户查询条件,可为空
* @return
*/
List<SysUserSysDepartModel> getUserByOrgCode(IPage page, @Param("orgCode") String orgCode, @Param("userParams") SysUser userParams);
/**
* 查询 getUserByOrgCode 的Total
*
* @param orgCode
* @param userParams 用户查询条件,可为空
* @return
*/
Integer getUserByOrgCodeTotal(@Param("orgCode") String orgCode, @Param("userParams") SysUser userParams);
}

View File

@ -18,4 +18,8 @@ public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
@Select("select role_code from sys_role where id in (select role_id from sys_user_role where user_id = (select id from sys_user where username=#{username}))")
List<String> getRoleByUserName(@Param("username") String username);
@Select("select id from sys_role where id in (select role_id from sys_user_role where user_id = (select id from sys_user where username=#{username}))")
List<String> getRoleIdByUserName(@Param("username") String username);
}

View File

@ -2,7 +2,7 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.jeecg.modules.system.mapper.SysCategoryMapper">
<select id="queryListByPid" parameterType="String" resultType="org.jeecg.modules.system.model.TreeSelectModel">
<select id="queryListByPid" parameterType="Object" resultType="org.jeecg.modules.system.model.TreeSelectModel">
select code,
name as "title",
id as "key",
@ -10,7 +10,12 @@
pid as parentId
from sys_category
where pid = #{pid}
<if test="query!= null">
<foreach collection="query.entrySet()" item="value" index="key" >
and ${key} = #{value}
</foreach>
</if>
</select>
</mapper>

View File

@ -5,4 +5,20 @@
<select id="queryUserDeparts" parameterType="String" resultType="org.jeecg.modules.system.entity.SysDepart">
select * from sys_depart where id IN ( select dep_id from sys_user_depart where user_id = #{userId} )
</select>
<!-- 根据username查询所拥有的部门 -->
<select id="queryDepartsByUsername" parameterType="String" resultType="org.jeecg.modules.system.entity.SysDepart">
SELECT *
FROM sys_depart
WHERE id IN (
SELECT dep_id
FROM sys_user_depart
WHERE user_id = (
SELECT id
FROM sys_user
WHERE username = #{username}
)
)
</select>
</mapper>

View File

@ -24,14 +24,25 @@
<!--通过查询指定table的 text code 获取字典(指定查询条件)-->
<select id="queryTableDictItemsByCodeAndFilter" parameterType="String" resultType="org.jeecg.common.system.vo.DictModel">
select ${text} as "text",${code} as "value" from ${table} where ${filterSql}
select ${text} as "text",${code} as "value" from ${table}
<if test="filterSql != null and filterSql != ''">
where ${filterSql}
</if>
</select>
<!--通过查询指定table的 text code key 获取字典值-->
<select id="queryTableDictTextByKey" parameterType="String" resultType="String">
<select id="queryTableDictTextByKey" parameterType="String" resultType="String">
select ${text} as "text" from ${table} where ${code}= #{key}
</select>
<!--通过查询指定table的 text code key 获取字典值包含value-->
<select id="queryTableDictByKeys" parameterType="String" resultType="org.jeecg.common.system.vo.DictModel">
select ${text} as "text", ${code} as "value" from ${table} where ${code} in
<foreach item="key" collection="keyArray" open="(" separator="," close=")">
#{key}
</foreach>
</select>
<!-- 重复校验 sql语句 -->
<select id="duplicateCheckCountSql" resultType="Long" parameterType="org.jeecg.modules.system.model.DuplicateCheckVo">
SELECT COUNT(*) FROM ${tableName} WHERE ${fieldName} = #{fieldVal} and id &lt;&gt; #{dataId}
@ -58,14 +69,28 @@
</select>
<!-- 根据表名、显示字段名、存储字段名、父ID查询树 -->
<select id="queryTreeList" parameterType="String" resultType="org.jeecg.modules.system.model.TreeSelectModel">
<select id="queryTreeList" parameterType="Object" resultType="org.jeecg.modules.system.model.TreeSelectModel">
select ${text} as "title",
${code} as "key",
<if test="hasChildField != null and hasChildField != ''">
(case ${hasChildField} when '1' then 0 else 1 end) as isLeaf,
(case when ${hasChildField} = '1' then 0 else 1 end) as isLeaf,
</if>
${pidField} as parentId
from ${table} where ${pidField} = #{pid}
from ${table}
where
<choose>
<when test="pid != null and pid != ''">
${pidField} = #{pid}
</when>
<otherwise>
(${pidField} = '' OR ${pidField} IS NULL)
</otherwise>
</choose>
<if test="query!= null">
<foreach collection="query.entrySet()" item="value" index="key" >
and ${key} = #{value}
</foreach>
</if>
</select>

View File

@ -24,14 +24,46 @@
<!-- 首页访问统计 -->
<select id="findVisitCount" resultType="java.util.HashMap">
select count(*) as visit,
count(distinct(ip)) as ip,
DATE_FORMAT(create_time, '%Y-%m-%d') as tian,
DATE_FORMAT(create_time, '%m-%d') as type
from sys_log
<if test="dbType == 'MYSQL'">
select count(*) as visit
,count(distinct(ip)) as ip
,DATE_FORMAT(create_time, '%Y-%m-%d') as tian
,DATE_FORMAT(create_time, '%m-%d') as type
from sys_log
where log_type = 1 and create_time &gt;= #{dayStart} and create_time &lt; #{dayEnd}
group by tian,type
order by tian asc
</if>
<if test="dbType == 'ORACLE'">
select count(*) as visit
,count(distinct(ip)) as ip
,to_char(create_time, 'yyyy-mm-dd') as tian
,to_char(create_time, 'mm-dd') as type
from sys_log
where log_type = 1 and create_time &gt;= #{dayStart} and create_time &lt; #{dayEnd}
group by to_char(create_time, 'yyyy-mm-dd'),to_char(create_time, 'mm-dd')
order by to_char(create_time, 'yyyy-mm-dd') asc
</if>
<if test="dbType == 'POSTGRESQL'">
select count(*) as visit
,count(distinct(ip)) as ip
,to_char(create_time, 'yyyy-mm-dd') as tian
,to_char(create_time, 'mm-dd') as type
from sys_log
where log_type = 1 and create_time &gt;= #{dayStart} and create_time &lt; #{dayEnd}
group by tian,type
order by tian asc
</if>
<if test="dbType == 'SQLSERVER'">
select count(*) as visit
,count(distinct(ip)) as ip
,CONVERT(varchar(100), create_time, 23) as tian
,RIGHT(CONVERT(varchar(100), create_time, 23),5) as type
from sys_log
where log_type = 1 and create_time &gt;= #{dayStart} and create_time &lt; #{dayEnd}
group by CONVERT(varchar(100), create_time, 23),RIGHT(CONVERT(varchar(100), create_time, 23),5)
order by CONVERT(varchar(100), create_time, 23) asc
</if>
</select>
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.jeecg.modules.system.mapper.SysPositionMapper">
</mapper>

View File

@ -37,5 +37,48 @@
<select id="getUserByEmail" resultType="org.jeecg.modules.system.entity.SysUser">
select * from sys_user where email = #{email} and del_flag = '0'
</select>
<!-- SQL片段getUserByOrgCode 的 FROM 和 WHERE 部分 -->
<sql id="getUserByOrgCodeFromSql">
FROM
sys_depart
-- 关联查询出该部门有哪些用户
INNER JOIN sys_user_depart ON sys_user_depart.dep_id = sys_depart.id
-- 关联查询出该用户的详细信息
INNER JOIN sys_user ON sys_user.id = sys_user_depart.user_id
WHERE
sys_depart.org_code LIKE '${orgCode}%'
<if test="userParams != null">
<if test="userParams.realname != null and userParams.realname != ''">
AND sys_user.realname LIKE '%${userParams.realname}%'
</if>
<if test="userParams.workNo != null and userParams.workNo != ''">
AND sys_user.work_no LIKE '%${userParams.workNo}%'
</if>
</if>
</sql>
<!-- 根据 orgCode 查询用户,包括子部门下的用户 -->
<select id="getUserByOrgCode" resultType="org.jeecg.modules.system.model.SysUserSysDepartModel">
SELECT
sys_user.id AS "sys_user.id",
sys_user.realname AS "sys_user.realname",
sys_user.work_no AS "sys_user.work_no",
sys_user.post AS "sys_user.post",
sys_user.telephone AS "sys_user.telephone",
sys_user.email AS "sys_user.email",
sys_user.phone AS "sys_user.phone",
sys_depart.id AS "sys_depart.id",
sys_depart.depart_name AS "sys_depart.depart_name"
<include refid="getUserByOrgCodeFromSql"/>
ORDER BY
sys_depart.org_code ASC
</select>
<!-- 查询 getUserByOrgCode 的总数-->
<select id="getUserByOrgCodeTotal" resultType="java.lang.Integer">
SELECT COUNT(1) <include refid="getUserByOrgCodeFromSql"/>
</select>
</mapper>

View File

@ -23,7 +23,7 @@ public class AnnouncementSendModel implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private java.lang.String id;
/**通告id*/
private java.lang.String anntId;

View File

@ -46,6 +46,8 @@ public class SysDepartTreeModel implements Serializable{
private Integer departOrder;
private Object description;
private String orgCategory;
private String orgType;
@ -89,6 +91,7 @@ public class SysDepartTreeModel implements Serializable{
this.departNameAbbr = sysDepart.getDepartNameAbbr();
this.departOrder = sysDepart.getDepartOrder();
this.description = sysDepart.getDescription();
this.orgCategory = sysDepart.getOrgCategory();
this.orgType = sysDepart.getOrgType();
this.orgCode = sysDepart.getOrgCode();
this.mobile = sysDepart.getMobile();
@ -179,8 +182,16 @@ public class SysDepartTreeModel implements Serializable{
public void setDepartName(String departName) {
this.departName = departName;
}
public String getOrgCategory() {
return orgCategory;
}
public String getOrgType() {
public void setOrgCategory(String orgCategory) {
this.orgCategory = orgCategory;
}
public String getOrgType() {
return orgType;
}
@ -329,6 +340,7 @@ public class SysDepartTreeModel implements Serializable{
Objects.equals(departNameAbbr, model.departNameAbbr) &&
Objects.equals(departOrder, model.departOrder) &&
Objects.equals(description, model.description) &&
Objects.equals(orgCategory, model.orgCategory) &&
Objects.equals(orgType, model.orgType) &&
Objects.equals(orgCode, model.orgCode) &&
Objects.equals(mobile, model.mobile) &&
@ -351,7 +363,7 @@ public class SysDepartTreeModel implements Serializable{
public int hashCode() {
return Objects.hash(id, parentId, departName, departNameEn, departNameAbbr,
departOrder, description, orgType, orgCode, mobile, fax, address,
departOrder, description, orgCategory, orgType, orgCode, mobile, fax, address,
memo, status, delFlag, createBy, createTime, updateBy, updateTime,
children);
}

View File

@ -34,7 +34,7 @@ public class SysDictTree implements Serializable {
/**
* id
*/
@TableId(type = IdType.UUID)
@TableId(type = IdType.ID_WORKER_STR)
private String id;
/**
* 字典类型,0 string,1 number类型,2 boolean

View File

@ -17,6 +17,8 @@ public class SysLoginModel {
private String password;
@ApiModelProperty(value = "验证码")
private String captcha;
@ApiModelProperty(value = "验证码key")
private String checkKey;
public String getUsername() {
return username;
@ -41,4 +43,13 @@ public class SysLoginModel {
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
public String getCheckKey() {
return checkKey;
}
public void setCheckKey(String checkKey) {
this.checkKey = checkKey;
}
}

View File

@ -60,7 +60,7 @@ public class SysPermissionTree implements Serializable {
/**
* 菜单排序
*/
private Integer sortNo;
private Double sortNo;
/**
* 类型0一级菜单1子菜单 2按钮权限
@ -122,6 +122,11 @@ public class SysPermissionTree implements Serializable {
/**按钮权限状态(0无效1有效)*/
private java.lang.String status;
/*update_begin author:wuxianquan date:20190908 for:model增加字段 */
/** 外链菜单打开方式 0/内部打开 1/外部打开 */
private boolean internalOrExternal;
/*update_end author:wuxianquan date:20190908 for:model增加字段 */
public SysPermissionTree() {
}
@ -150,6 +155,9 @@ public class SysPermissionTree implements Serializable {
this.route = permission.isRoute();
this.keepAlive = permission.isKeepAlive();
this.alwaysShow= permission.isAlwaysShow();
/*update_begin author:wuxianquan date:20190908 for:赋值 */
this.internalOrExternal = permission.isInternalOrExternal();
/*update_end author:wuxianquan date:20190908 for:赋值 */
this.title=permission.getName();
if (!permission.isLeaf()) {
this.children = new ArrayList<SysPermissionTree>();
@ -262,11 +270,11 @@ public class SysPermissionTree implements Serializable {
this.url = url;
}
public Integer getSortNo() {
public Double getSortNo() {
return sortNo;
}
public void setSortNo(Integer sortNo) {
public void setSortNo(Double sortNo) {
this.sortNo = sortNo;
}
@ -374,5 +382,13 @@ public class SysPermissionTree implements Serializable {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */
public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
}

View File

@ -0,0 +1,18 @@
package org.jeecg.modules.system.model;
import lombok.Data;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
/**
* 包含 SysUser 和 SysDepart 的 Model
*
* @author sunjianlei
*/
@Data
public class SysUserSysDepartModel {
private SysUser sysUser;
private SysDepart sysDepart;
}

View File

@ -1,6 +1,7 @@
package org.jeecg.modules.system.service;
import java.util.List;
import java.util.Map;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.system.entity.SysCategory;
@ -36,5 +37,20 @@ public interface ISysCategoryService extends IService<SysCategory> {
* @return
*/
public List<TreeSelectModel> queryListByPid(String pid);
/**
* 根据pid查询子节点集合,支持查询条件
* @param pid
* @param condition
* @return
*/
public List<TreeSelectModel> queryListByPid(String pid, Map<String,String> condition);
/**
* 根据code查询id
* @param code
* @return
*/
public String queryIdByCode(String code);
}

View File

@ -70,7 +70,14 @@ public interface ISysDepartService extends IService<SysDepart>{
*/
public List<SysDepart> queryUserDeparts(String userId);
/**
* 根据用户名查询部门
*
* @param username
* @return
*/
List<SysDepart> queryDepartsByUsername(String username);
/**
* 根据部门id批量删除并删除其可能存在的子级部门
* @param id

View File

@ -27,7 +27,9 @@ public interface ISysDictService extends IService<SysDict> {
public String queryDictTextByKey(String code, String key);
String queryTableDictTextByKey(String table, String text, String code, String key);
String queryTableDictTextByKey(String table, String text, String code, String key);
List<String> queryTableDictByKeys(String table, String text, String code, String[] keyArray);
/**
* 根据字典类型删除关联表中其对应的数据
@ -74,6 +76,26 @@ public interface ISysDictService extends IService<SysDict> {
* @param hasChildField
* @return
*/
List<TreeSelectModel> queryTreeList(String table, String text, String code, String pidField,String pid,String hasChildField);
List<TreeSelectModel> queryTreeList(Map<String, String> query,String table, String text, String code, String pidField,String pid,String hasChildField);
/**
* 真实删除
* @param id
*/
public void deleteOneDictPhysically(String id);
/**
* 修改delFlag
* @param delFlag
* @param id
*/
public void updateDictDelFlag(int delFlag,String id);
/**
* 查询被逻辑删除的数据
* @return
*/
public List<SysDict> queryDeleteList();
}

View File

@ -0,0 +1,14 @@
package org.jeecg.modules.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.system.entity.SysPosition;
/**
* @Description: 职务表
* @Author: jeecg-boot
* @Date: 2019-09-19
* @Version: V1.0
*/
public interface ISysPositionService extends IService<SysPosition> {
}

View File

@ -1,12 +1,10 @@
package org.jeecg.modules.system.service;
import org.jeecg.modules.system.entity.SysRole;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
@ -17,6 +15,15 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2018-12-19
*/
public interface ISysRoleService extends IService<SysRole> {
/**
* 导入 excel ,检查 roleCode 的唯一性
*
* @param file
* @param params
* @return
* @throws Exception
*/
Result importExcelCheckRoleCode(MultipartFile file, ImportParams params) throws Exception;
}

View File

@ -3,6 +3,7 @@ package org.jeecg.modules.system.service;
import java.util.List;
import java.util.Set;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@ -11,6 +12,7 @@ import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.modules.system.entity.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
/**
* <p>
@ -21,6 +23,39 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2018-12-20
*/
public interface ISysUserService extends IService<SysUser> {
/**
* 重置密码
*
* @param username
* @param oldpassword
* @param newpassword
* @param confirmpassword
* @return
*/
public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword);
/**
* 修改密码
*
* @param sysUser
* @return
*/
public Result<?> changePassword(SysUser sysUser);
/**
* 删除用户
* @param userId
* @return
*/
public boolean deleteUser(String userId);
/**
* 批量删除用户
* @param userIds
* @return
*/
public boolean deleteBatchUsers(String userIds);
public SysUser getUserByName(String username);
@ -60,6 +95,26 @@ public interface ISysUserService extends IService<SysUser> {
*/
public IPage<SysUser> getUserByDepId(Page<SysUser> page, String departId, String username);
/**
* 根据部门 Id 和 QueryWrapper 查询
*
* @param page
* @param departId
* @param queryWrapper
* @return
*/
public IPage<SysUser> getUserByDepartIdAndQueryWrapper(Page<SysUser> page, String departId, QueryWrapper<SysUser> queryWrapper);
/**
* 根据 orgCode 查询用户,包括子部门下的用户
*
* @param orgCode
* @param userParams 用户查询条件,可为空
* @param page 分页参数
* @return
*/
IPage<SysUserSysDepartModel> queryUserByOrgCode(String orgCode, SysUser userParams, IPage page);
/**
* 根据角色Id查询
* @param

View File

@ -11,29 +11,27 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.ComboModel;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysAnnouncementSend;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysAnnouncementMapper;
import org.jeecg.modules.system.mapper.SysAnnouncementSendMapper;
import org.jeecg.modules.system.mapper.SysLogMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.mapper.*;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
@ -50,10 +48,7 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class SysBaseApiImpl implements ISysBaseAPI {
public static final String DB_TYPE_MYSQL="MYSQL";
public static final String DB_TYPE_ORACLE="ORACLE";
public static final String DB_TYPE_POSTGRESQL="POSTGRESQL";
public static final String DB_TYPE_SQLSERVER="SQLSERVER";
/** 当前系统数据库类型 */
public static String DB_TYPE = "";
@Resource
@ -63,6 +58,8 @@ public class SysBaseApiImpl implements ISysBaseAPI {
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private ISysDepartService sysDepartService;
@Autowired
private ISysDictService sysDictService;
@Resource
private SysAnnouncementMapper sysAnnouncementMapper;
@ -70,6 +67,10 @@ public class SysBaseApiImpl implements ISysBaseAPI {
private SysAnnouncementSendMapper sysAnnouncementSendMapper;
@Resource
private WebSocket webSocket;
@Resource
private SysRoleMapper roleMapper;
@Resource
private SysDepartMapper departMapper;
@Override
public void addLog(String LogContent, Integer logType, Integer operatetype) {
@ -104,6 +105,7 @@ public class SysBaseApiImpl implements ISysBaseAPI {
}
@Override
@Cacheable(cacheNames=CacheConstant.SYS_USERS_CACHE, key="#username")
public LoginUser getUserByName(String username) {
if(oConvertUtils.isEmpty(username)) {
return null;
@ -116,12 +118,46 @@ public class SysBaseApiImpl implements ISysBaseAPI {
BeanUtils.copyProperties(sysUser, loginUser);
return loginUser;
}
@Override
public LoginUser getUserById(String id) {
if(oConvertUtils.isEmpty(id)) {
return null;
}
LoginUser loginUser = new LoginUser();
SysUser sysUser = userMapper.selectById(id);
if(sysUser==null) {
return null;
}
BeanUtils.copyProperties(sysUser, loginUser);
return loginUser;
}
@Override
public List<String> getRolesByUsername(String username) {
return sysUserRoleMapper.getRoleByUserName(username);
}
@Override
public List<String> getDepartIdsByUsername(String username) {
List<SysDepart> list = sysDepartService.queryDepartsByUsername(username);
List<String> result = new ArrayList<>(list.size());
for (SysDepart depart : list) {
result.add(depart.getId());
}
return result;
}
@Override
public List<String> getDepartNamesByUsername(String username) {
List<SysDepart> list = sysDepartService.queryDepartsByUsername(username);
List<String> result = new ArrayList<>(list.size());
for (SysDepart depart : list) {
result.add(depart.getDepartName());
}
return result;
}
@Override
public String getDatabaseType() throws SQLException {
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
@ -186,7 +222,6 @@ public class SysBaseApiImpl implements ISysBaseAPI {
* @param dataSource
* @return
* @throws SQLException
* @throws DBException
*/
private String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
if("".equals(DB_TYPE)) {
@ -195,13 +230,13 @@ public class SysBaseApiImpl implements ISysBaseAPI {
DatabaseMetaData md = connection.getMetaData();
String dbType = md.getDatabaseProductName().toLowerCase();
if(dbType.indexOf("mysql")>=0) {
DB_TYPE = DB_TYPE_MYSQL;
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
}else if(dbType.indexOf("oracle")>=0) {
DB_TYPE = DB_TYPE_ORACLE;
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
DB_TYPE = DB_TYPE_SQLSERVER;
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf("postgresql")>=0) {
DB_TYPE = DB_TYPE_POSTGRESQL;
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else {
throw new JeecgBootException("数据库类型:["+dbType+"]不识别!");
}
@ -229,4 +264,52 @@ public class SysBaseApiImpl implements ISysBaseAPI {
return list;
}
@Override
public List<DictModel> queryFilterTableDictInfo(String table, String text, String code, String filterSql) {
return sysDictService.queryTableDictItemsByCodeAndFilter(table,text,code,filterSql);
}
@Override
public List<ComboModel> queryAllUser() {
List<ComboModel> list = new ArrayList<ComboModel>();
List<SysUser> userList = userMapper.selectList(new QueryWrapper<SysUser>().eq("status","1").eq("del_flag","0"));
for(SysUser user : userList){
ComboModel model = new ComboModel();
model.setTitle(user.getRealname());
model.setId(user.getId());
list.add(model);
}
return list;
}
@Override
public List<ComboModel> queryAllRole() {
List<ComboModel> list = new ArrayList<ComboModel>();
List<SysRole> roleList = roleMapper.selectList(new QueryWrapper<SysRole>());
for(SysRole role : roleList){
ComboModel model = new ComboModel();
model.setTitle(role.getRoleName());
model.setId(role.getId());
list.add(model);
}
return list;
}
@Override
public List<String> getRoleIdsByUsername(String username) {
return sysUserRoleMapper.getRoleIdByUserName(username);
}
@Override
public String getDepartIdsByOrgCode(String orgCode) {
return departMapper.queryDepartIdByOrgCode(orgCode);
}
@Override
public DictModel getParentDepartId(String departId) {
SysDepart depart = departMapper.getParentDepartId(departId);
DictModel model = new DictModel(depart.getId(),depart.getParentId());
return model;
}
}

View File

@ -1,8 +1,10 @@
package org.jeecg.modules.system.service.impl;
import java.util.List;
import java.util.Map;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.mapper.SysCategoryMapper;
@ -24,16 +26,47 @@ public class SysCategoryServiceImpl extends ServiceImpl<SysCategoryMapper, SysCa
@Override
public void addSysCategory(SysCategory sysCategory) {
if(oConvertUtils.isEmpty(sysCategory.getPid())){
sysCategory.setPid(ISysCategoryService.ROOT_PID_VALUE);
}else{
//如果当前节点父ID不为空 则设置父节点的hasChild 为1
SysCategory parent = baseMapper.selectById(sysCategory.getPid());
if(parent!=null && !"1".equals(parent.getHasChild())){
parent.setHasChild("1");
baseMapper.updateById(parent);
String categoryCode = "";
String categoryPid = ISysCategoryService.ROOT_PID_VALUE;
String parentCode = null;
if(oConvertUtils.isNotEmpty(sysCategory.getPid())){
categoryPid = sysCategory.getPid();
//PID 不是根节点 说明需要设置父节点 hasChild 为1
if(!ISysCategoryService.ROOT_PID_VALUE.equals(categoryPid)){
SysCategory parent = baseMapper.selectById(categoryPid);
parentCode = parent.getCode();
if(parent!=null && !"1".equals(parent.getHasChild())){
parent.setHasChild("1");
baseMapper.updateById(parent);
}
}
}
/*
* 分成三种情况
* 1.数据库无数据 调用YouBianCodeUtil.getNextYouBianCode(null);
* 2.添加子节点,无兄弟元素 YouBianCodeUtil.getSubYouBianCode(parentCode,null);
* 3.添加子节点有兄弟元素 YouBianCodeUtil.getNextYouBianCode(lastCode);
* */
//找同类 确定上一个最大的code值
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>()
.eq(SysCategory::getPid,categoryPid)
.orderByDesc(SysCategory::getCode);
List<SysCategory> list = baseMapper.selectList(query);
if(list==null || list.size()==0){
if(ISysCategoryService.ROOT_PID_VALUE.equals(categoryPid)){
//情况1
categoryCode = YouBianCodeUtil.getNextYouBianCode(null);
}else{
//情况2
categoryCode = YouBianCodeUtil.getSubYouBianCode(parentCode,null);
}
}else{
//情况3
categoryCode = YouBianCodeUtil.getNextYouBianCode(list.get(0).getCode());
}
sysCategory.setCode(categoryCode);
sysCategory.setPid(categoryPid);
baseMapper.insert(sysCategory);
}
@ -65,7 +98,7 @@ public class SysCategoryServiceImpl extends ServiceImpl<SysCategoryMapper, SysCa
}
pid = list.get(0).getId();
}
return baseMapper.queryListByPid(pid);
return baseMapper.queryListByPid(pid,null);
}
@Override
@ -73,7 +106,20 @@ public class SysCategoryServiceImpl extends ServiceImpl<SysCategoryMapper, SysCa
if(oConvertUtils.isEmpty(pid)) {
pid = ROOT_PID_VALUE;
}
return baseMapper.queryListByPid(pid);
return baseMapper.queryListByPid(pid,null);
}
@Override
public List<TreeSelectModel> queryListByPid(String pid, Map<String, String> condition) {
if(oConvertUtils.isEmpty(pid)) {
pid = ROOT_PID_VALUE;
}
return baseMapper.queryListByPid(pid,condition);
}
@Override
public String queryIdByCode(String code) {
return baseMapper.queryIdByCode(code);
}
}

View File

@ -37,7 +37,7 @@ public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart
/**
* queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
*/
@Cacheable(value = CacheConstant.DEPART_INFO_CACHE)
@Cacheable(value = CacheConstant.SYS_DEPARTS_CACHE)
@Override
public List<SysDepartTreeModel> queryTreeList() {
LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
@ -49,7 +49,7 @@ public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart
return listResult;
}
@Cacheable(value = CacheConstant.DEPART_IDMODEL_CACHE)
@Cacheable(value = CacheConstant.SYS_DEPART_IDS_CACHE)
@Override
public List<DepartIdModel> queryDepartIdTreeList() {
LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
@ -109,7 +109,7 @@ public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart
// 如果是最高级,则查询出同级的org_code, 调用工具类生成编码并返回
if (StringUtil.isNullOrEmpty(parentId)) {
// 线判断数据库中的表是否为空,空则直接返回初始编码
query1.eq(SysDepart::getParentId, "");
query1.eq(SysDepart::getParentId, "").or().isNull(SysDepart::getParentId);
query1.orderByDesc(SysDepart::getOrgCode);
departList = this.list(query1);
if(departList == null || departList.size() == 0) {
@ -254,6 +254,10 @@ public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart
public List<SysDepart> queryUserDeparts(String userId) {
return baseMapper.queryUserDeparts(userId);
}
@Override
public List<SysDepart> queryDepartsByUsername(String username) {
return baseMapper.queryDepartsByUsername(username);
}
}

View File

@ -1,7 +1,10 @@
package org.jeecg.modules.system.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.DictModel;
@ -43,7 +46,7 @@ public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> impl
* @return
*/
@Override
@Cacheable(value = CacheConstant.DICT_CACHE,key = "#code")
@Cacheable(value = CacheConstant.SYS_DICT_CACHE,key = "#code")
public List<DictModel> queryDictItemsByCode(String code) {
log.info("无缓存dictCache的时候调用这里");
return sysDictMapper.queryDictItemsByCode(code);
@ -57,7 +60,7 @@ public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> impl
*/
@Override
@Cacheable(value = CacheConstant.DICT_CACHE)
@Cacheable(value = CacheConstant.SYS_DICT_CACHE,key = "#code+':'+#key")
public String queryDictTextByKey(String code, String key) {
log.info("无缓存dictText的时候调用这里");
return sysDictMapper.queryDictTextByKey(code, key);
@ -72,7 +75,7 @@ public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> impl
* @return
*/
@Override
//@Cacheable(value = "dictTableCache")
//@Cacheable(value = CacheConstant.SYS_DICT_TABLE_CACHE)
public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {
log.info("无缓存dictTableList的时候调用这里");
return sysDictMapper.queryTableDictItemsByCode(table,text,code);
@ -94,12 +97,38 @@ public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> impl
* @return
*/
@Override
@Cacheable(value = "dictTableCache")
@Cacheable(value = CacheConstant.SYS_DICT_TABLE_CACHE)
public String queryTableDictTextByKey(String table,String text,String code, String key) {
log.info("无缓存dictTable的时候调用这里");
return sysDictMapper.queryTableDictTextByKey(table,text,code,key);
}
/**
* 通过查询指定table的 text code 获取字典包含text和value
* dictTableCache采用redis缓存有效期10分钟
* @param table
* @param text
* @param code
* @param keyArray
* @return
*/
@Override
@Cacheable(value = CacheConstant.SYS_DICT_TABLE_CACHE)
public List<String> queryTableDictByKeys(String table, String text, String code, String[] keyArray) {
List<DictModel> dicts = sysDictMapper.queryTableDictByKeys(table, text, code, keyArray);
List<String> texts = new ArrayList<>(dicts.size());
// 查询出来的顺序可能是乱的,需要排个序
for (String key : keyArray) {
for (DictModel dict : dicts) {
if (key.equals(dict.getValue())) {
texts.add(dict.getText());
break;
}
}
}
return texts;
}
/**
* 根据字典类型id删除关联表中其对应的数据
*/
@ -138,8 +167,23 @@ public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> impl
}
@Override
public List<TreeSelectModel> queryTreeList(String table, String text, String code, String pidField,String pid,String hasChildField) {
return baseMapper.queryTreeList(table, text, code, pidField, pid,hasChildField);
public List<TreeSelectModel> queryTreeList(Map<String, String> query,String table, String text, String code, String pidField,String pid,String hasChildField) {
return baseMapper.queryTreeList(query,table, text, code, pidField, pid,hasChildField);
}
@Override
public void deleteOneDictPhysically(String id) {
this.baseMapper.deleteOneById(id);
this.sysDictItemMapper.delete(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId,id));
}
@Override
public void updateDictDelFlag(int delFlag, String id) {
baseMapper.updateDictDelFlag(delFlag,id);
}
@Override
public List<SysDict> queryDeleteList() {
return baseMapper.queryDeleteList();
}
}

View File

@ -1,14 +1,17 @@
package org.jeecg.modules.system.service.impl;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.mapper.SysLogMapper;
import org.jeecg.modules.system.service.ISysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -26,6 +29,8 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
@Resource
private SysLogMapper sysLogMapper;
@Autowired
private ISysBaseAPI sysBaseAPI;
/**
* @功能:清空所有日志记录
@ -54,6 +59,11 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
@Override
public List<Map<String,Object>> findVisitCount(Date dayStart, Date dayEnd) {
return sysLogMapper.findVisitCount(dayStart, dayEnd);
try {
String dbType = sysBaseAPI.getDatabaseType();
return sysLogMapper.findVisitCount(dayStart, dayEnd,dbType);
} catch (SQLException e) {
}
return null;
}
}

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