Compare commits

..

No commits in common. '8375311bc4114731286fbdf014787d4da225f2e6' and 'a524fc12c98f08676a03d45e953fc3c68c9aacaa' have entirely different histories.

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="17 (2)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>

@ -2,6 +2,7 @@
<module type="JAVA_MODULE" version="4"> <module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true"> <component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output /> <exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>

@ -1,124 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

@ -8,29 +8,16 @@ import org.slf4j.LoggerFactory;
/** /**
* , * ,
*/ */
// 可以将 @Component 注释添加在这里,以将该类注册为 Spring 组件 //@Component
public class MyMetaObjectHandler extends MetaObjectHandler { public class MyMetaObjectHandler extends MetaObjectHandler {
// 定义一个静态的日志记录器
protected final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class); protected final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);
/**
*
*
* @param metaObject
*/
@Override @Override
public void insertFill(MetaObject metaObject) { public void insertFill(MetaObject metaObject) {
} }
/**
*
*
*
* @param metaObject
*/
@Override @Override
public void updateFill(MetaObject metaObject) { public void updateFill(MetaObject metaObject) {
} }
} }

@ -19,58 +19,50 @@ import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.LongValue;
/** @Configuration
* MybatisPlusConfig Mybatis-Plus @MapperScan("com.tamguo.modules.*.dao*")
*/
@Configuration // 表示这是一个配置类
@MapperScan("com.tamguo.modules.*.dao*") // 扫描指定包下的 Mapper 接口
public class MybatisPlusConfig { public class MybatisPlusConfig {
/**
* PerformanceInterceptor
* @return PerformanceInterceptor
*/
@Bean @Bean
public PerformanceInterceptor performanceInterceptor() { public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor(); // 创建并返回性能拦截器实例 return new PerformanceInterceptor();
} }
/** /**
* PaginationInterceptor * mybatis-plus<br>
* @return PaginationInterceptor * http://mp.baomidou.com<br>
*/ */
@Bean @Bean
public PaginationInterceptor paginationInterceptor() { public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 创建分页拦截器实例 PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setLocalPage(true); // 开启 PageHelper 的支持 paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
/* /*
* SQL * SQL <br>
* 1 cookie SQL <br>
*/ */
List<ISqlParser> sqlParserList = new ArrayList<>(); // 创建 SQL 解析器列表 List<ISqlParser> sqlParserList = new ArrayList<>();
TenantSqlParser tenantSqlParser = new TenantSqlParser(); // 创建租户 SQL 解析器实例 TenantSqlParser tenantSqlParser = new TenantSqlParser();
tenantSqlParser.setTenantHandler(new TenantHandler() {
tenantSqlParser.setTenantHandler(new TenantHandler() { // 设置租户处理逻辑
@Override @Override
public Expression getTenantId() { public Expression getTenantId() {
return new LongValue(1L); // 返回表示租户 ID 的表达式 return new LongValue(1L);
} }
@Override @Override
public String getTenantIdColumn() { public String getTenantIdColumn() {
return "course_id"; // 返回租户 ID 所在的列名 return "course_id";
} }
@Override @Override
public boolean doTableFilter(String tableName) { public boolean doTableFilter(String tableName) {
// 这里可以判断是否过滤表 // 这里可以判断是否过滤表
return true; // 返回是否过滤表的标志 return true;
} }
}); });
sqlParserList.add(tenantSqlParser); // 将租户 SQL 解析器添加到列表中
paginationInterceptor.setSqlParserList(sqlParserList); // 设置分页拦截器的 SQL 解析器列表
sqlParserList.add(tenantSqlParser);
paginationInterceptor.setSqlParserList(sqlParserList);
// 以下过滤方式与 @SqlParser(filter = true) 注解等效 // 以下过滤方式与 @SqlParser(filter = true) 注解等效
// paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() { // paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
// @Override // @Override
@ -86,23 +78,16 @@ public class MybatisPlusConfig {
return paginationInterceptor; return paginationInterceptor;
} }
/**
* MetaObjectHandler
* @return MetaObjectHandler
*/
@Bean @Bean
public MetaObjectHandler metaObjectHandler(){ public MetaObjectHandler metaObjectHandler(){
return new MyMetaObjectHandler(); // 创建并返回元对象处理实例 return new MyMetaObjectHandler();
} }
/** /**
* * sql
* ISqlInjector
* @return ISqlInjector SQL
*/ */
@Bean @Bean
public ISqlInjector sqlInjector(){ public ISqlInjector sqlInjector(){
return new LogicSqlInjector(); // 创建并返回逻辑 SQL 注入器实例 return new LogicSqlInjector();
} }
} }

@ -1,7 +1,6 @@
package com.tamguo.config.shiro; package com.tamguo.config.shiro;
import java.util.Set; import java.util.Set;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.AuthenticationToken;
@ -13,87 +12,61 @@ import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.tamguo.modules.member.model.MemberEntity; import com.tamguo.modules.member.model.MemberEntity;
import com.tamguo.modules.member.service.IMemberService; import com.tamguo.modules.member.service.IMemberService;
/** /**
* Realm *
* *
*/ */
public class MemberRealm extends AuthorizingRealm { public class MemberRealm extends AuthorizingRealm {
// 依赖注入 MemberService 实例
@Autowired @Autowired
private IMemberService iMemberService; private IMemberService iMemberService;
/** /**
* * ()
* */
* @param principals
* @return
*/
@Override @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 权限集合 Set<String > permsSet = null;
Set<String> permsSet = null;
// 创建简单授权信息对象
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 设置权限集合
info.setStringPermissions(permsSet); info.setStringPermissions(permsSet);
return info; return info;
} }
/** /**
* * ()
*
* @param token
* @return
* @throws AuthenticationException
*/ */
@Override @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { protected AuthenticationInfo doGetAuthenticationInfo(
// 获取用户名 AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal(); String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
// 获取密码
String password = new String((char[]) token.getCredentials()); MemberEntity member = iMemberService.findByUsername(username);
if(member == null) {
// 根据用户名查询 MemberEntity 对象 throw new UnknownAccountException("用户名或密码有误,请重新输入或找回密码");
MemberEntity member = iMemberService.findByUsername(username); }
Integer loginFailureCount = iMemberService.getLoginFailureCount(member);
// 如果用户不存在 if(loginFailureCount > 10) {
if (member == null) { throw new LockedAccountException("账号被锁定");
throw new UnknownAccountException("用户名或密码有误,请重新输入或找回密码"); }
}
if(!new Sha256Hash(password).toHex().equals(member.getPassword())){
// 获取登录失败次数
Integer loginFailureCount = iMemberService.getLoginFailureCount(member);
// 如果登录失败次数大于 10
if (loginFailureCount > 10) {
throw new LockedAccountException("账号被锁定");
}
// 如果密码不匹配
if (!new Sha256Hash(password).toHex().equals(member.getPassword())) {
loginFailureCount++; loginFailureCount++;
iMemberService.updateLoginFailureCount(member, loginFailureCount); iMemberService.updateLoginFailureCount(member , loginFailureCount);
throw new IncorrectCredentialsException("用户名或密码有误,请重新输入或找回密码"); throw new IncorrectCredentialsException("用户名或密码有误,请重新输入或找回密码");
} }
// 更新登录时间 // 更新登录时间
iMemberService.updateLastLoginTime(member.getId()); iMemberService.updateLastLoginTime(member.getId());
// 创建简单认证信息对象 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(member, password, getName());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(member, password, getName()); return info;
return info;
} }
}
}

@ -12,96 +12,55 @@ import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreato
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/**
* Shiro
*/
@Configuration @Configuration
public class ShiroConfiguration { public class ShiroConfiguration {
// 定义过滤链定义映射,用于配置 Shiro 的权限控制规则
private static Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); private static Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
/**
* Shiro MemberRealm
* @return MemberRealm
*/
@Bean(name = "shiroRealm") @Bean(name = "shiroRealm")
public MemberRealm getShiroRealm() { public MemberRealm getShiroRealm() {
// 创建 MemberRealm 实例
return new MemberRealm(); return new MemberRealm();
} }
/**
* EhCache Shiro
* @return EhCacheManager
*/
@Bean(name = "shiroEhcacheManager") @Bean(name = "shiroEhcacheManager")
public EhCacheManager getEhCacheManager() { public EhCacheManager getEhCacheManager() {
// 创建 EhCacheManager 实例,并设置其配置文件路径
EhCacheManager em = new EhCacheManager(); EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return em; return em;
} }
/**
* Bean Shiro Bean
* @return LifecycleBeanPostProcessor
*/
@Bean(name = "lifecycleBeanPostProcessor") @Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
// 创建 LifecycleBeanPostProcessor 实例
return new LifecycleBeanPostProcessor(); return new LifecycleBeanPostProcessor();
} }
/**
*
* @return DefaultAdvisorAutoProxyCreator
*/
@Bean @Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() { public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
// 创建 DefaultAdvisorAutoProxyCreator 实例,并设置代理目标类为 true
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator(); DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true); daap.setProxyTargetClass(true);
return daap; return daap;
} }
/**
* Web Shiro
* @return DefaultWebSecurityManager
*/
@Bean(name = "securityManager") @Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager() { public DefaultWebSecurityManager getDefaultWebSecurityManager() {
// 创建 DefaultWebSecurityManager 实例,并设置相关属性
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager(); DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(getShiroRealm()); dwsm.setRealm(getShiroRealm());
dwsm.setCacheManager(getEhCacheManager()); dwsm.setCacheManager(getEhCacheManager());
return dwsm; return dwsm;
} }
/**
* Spring AOP
* @return AuthorizationAttributeSourceAdvisor
*/
@Bean @Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor() { public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor() {
// 创建 AuthorizationAttributeSourceAdvisor 实例,并设置相关属性
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor(); AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(getDefaultWebSecurityManager()); aasa.setSecurityManager(getDefaultWebSecurityManager());
return aasa; return new AuthorizationAttributeSourceAdvisor();
} }
/**
* Shiro Bean Shiro
* @return ShiroFilterFactoryBean
*/
@Bean(name = "shiroFilter") @Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean() { public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
// 创建 ShiroFilterFactoryBean 实例,并设置相关属性
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager()); shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index"); shiroFilterFactoryBean.setSuccessUrl("/index");
// 设置过滤链定义映射
filterChainDefinitionMap.put("/member/**", "authc"); filterChainDefinitionMap.put("/member/**", "authc");
filterChainDefinitionMap.put("/**", "anon"); filterChainDefinitionMap.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

@ -6,33 +6,16 @@ import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* ErrorPageRegistrar
*/
@Component @Component
public class ErrorConfigurar implements ErrorPageRegistrar { public class ErrorConfigurar implements ErrorPageRegistrar {
/**
*
*
* @param registry
*/
@Override @Override
public void registerErrorPages(ErrorPageRegistry registry) { public void registerErrorPages(ErrorPageRegistry registry) {
// 创建一个错误页面数组 ErrorPage[] errorPages=new ErrorPage[2];
ErrorPage[] errorPages = new ErrorPage[2]; errorPages[0]=new ErrorPage(HttpStatus.NOT_FOUND,"/error404");
errorPages[1]=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/error500");
// 创建一个表示 404 状态的错误页面,并指定其重定向路径 registry.addErrorPages(errorPages);
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error404");
// 创建一个表示 500 状态的错误页面,并指定其重定向路径
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error500");
// 将两个错误页面添加到错误页面数组中
errorPages[0] = errorPage404;
errorPages[1] = errorPage500;
// 将错误页面数组添加到错误页面注册表中
registry.addErrorPages(errorPages);
} }
}
}

@ -10,83 +10,32 @@ import org.springframework.stereotype.Component;
import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import com.tamguo.common.utils.SystemConstant; import com.tamguo.common.utils.SystemConstant;
/**
* ThymeleafConfig EnvironmentAware
*/
@Component @Component
public class ThymeleafConfig implements EnvironmentAware { public class ThymeleafConfig implements EnvironmentAware{
/**
*
*/
@Resource @Resource
private Environment env; private Environment env;
/**
* Thymeleaf
* @param viewResolver ThymeleafViewResolver
*/
@Resource @Resource
private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) { private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
if (viewResolver!= null) { if(viewResolver != null) {
/** Map<String, Object> vars = new HashMap<>();
* Map vars.put("domainName", env.getProperty("domain.name"));
*/ vars.put("bookDomainName", env.getProperty("book.domain.name"));
Map<String, Object> vars = new HashMap<>(); vars.put("tamguoDomainName", env.getProperty("tamguo.domain.name"));
vars.put("PAPER_TYPE_ZHENTI", SystemConstant.ZHENGTI_PAPER_ID);
/** vars.put("PAPER_TYPE_MONI", SystemConstant.MONI_PAPER_ID);
* domain.name vars.put("PAPER_TYPE_YATI", SystemConstant.YATI_PAPER_ID);
*/ vars.put("PAPER_TYPE_MINGXIAO", SystemConstant.MINGXIAO_PAPER_ID);
vars.put("domainName", env.getProperty("domain.name")); vars.put("BEIJING_AREA_ID", SystemConstant.BEIJING_AREA_ID);
viewResolver.setStaticVariables(vars);
/** }
* book.domain.name
*/
vars.put("bookDomainName", env.getProperty("book.domain.name"));
/**
* tamguo.domain.name
*/
vars.put("tamguoDomainName", env.getProperty("tamguo.domain.name"));
/**
* ZHENGTI_PAPER_ID
*/
vars.put("PAPER_TYPE_ZHENTI", SystemConstant.ZHENGTI_PAPER_ID);
/**
* MONI_PAPER_ID
*/
vars.put("PAPER_TYPE_MONI", SystemConstant.MONI_PAPER_ID);
/**
* YATI_PAPER_ID
*/
vars.put("PAPER_TYPE_YATI", SystemConstant.YATI_PAPER_ID);
/**
* MINGXIAO_PAPER_ID
*/
vars.put("PAPER_TYPE_MINGXIAO", SystemConstant.MINGXIAO_PAPER_ID);
/**
* BEIJING_AREA_ID
*/
vars.put("BEIJING_AREA_ID", SystemConstant.BEIJING_AREA_ID);
/**
* ThymeleafViewResolver
*/
viewResolver.setStaticVariables(vars);
}
} }
/**
* EnvironmentAware
* @param environment
*/
@Override @Override
public void setEnvironment(Environment environment) { public void setEnvironment(Environment environment) {
env = environment; env = environment;
} }
}
}

@ -12,64 +12,36 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.tamguo.web.interceptor.MemberInterceptor; import com.tamguo.web.interceptor.MemberInterceptor;
/**
* WebConfig WebMvcConfigurer Web
*/
@Configuration @Configuration
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
/** @Value("${file.storage.path}")
* private String fileStoragePath;
*/ @Value("${cookie.domian.name}")
@Value("${file.storage.path}") private String cookieDomianName;
private String fileStoragePath;
@Autowired
/** private MemberInterceptor memberInterceptor;
* Cookie
*/
@Value("${cookie.domian.name}") @Override
private String cookieDomianName; public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(memberInterceptor).addPathPatterns("/**").excludePathPatterns("/login.html","/register.html","/password/**","/captcha.jpg" , "/submitLogin.html" , "/miniLogin.html","/static/**","/sendFindPasswordSms","/subRegister","/checkMobile.html","/checkUsername.html");
/** }
* MemberInterceptor
*/
@Autowired
private MemberInterceptor memberInterceptor;
/**
* addInterceptors
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器,并设置拦截路径和排除路径
registry.addInterceptor(memberInterceptor).addPathPatterns("/**").excludePathPatterns("/login.html", "/register.html", "/password/**", "/captcha.jpg", "/submitLogin.html", "/miniLogin.html", "/static/**", "/sendFindPasswordSms", "/subRegister", "/checkMobile.html", "/checkUsername.html");
}
/**
* addResourceHandlers
* @param registry
*/
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 添加资源处理器,处理/files/** 路径的资源,并设置资源位置为文件系统中的指定路径 registry.addResourceHandler("/files/**").addResourceLocations("file:"+fileStoragePath);
registry.addResourceHandler("/files/**").addResourceLocations("file:" + fileStoragePath);
} }
/**
* CookieSerializer
* @return CookieSerializer
*/
@Bean @Bean
public CookieSerializer defaultCookieSerializer() { public CookieSerializer defaultCookieSerializer(){
// 创建默认的 CookieSerializer 实例
DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer(); DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
// 设置 Cookie 名称
defaultCookieSerializer.setCookieName("sessionId"); defaultCookieSerializer.setCookieName("sessionId");
// 设置 Cookie 域名
defaultCookieSerializer.setDomainName(cookieDomianName); defaultCookieSerializer.setDomainName(cookieDomianName);
// 设置 Cookie 路径
defaultCookieSerializer.setCookiePath("/"); defaultCookieSerializer.setCookiePath("/");
return defaultCookieSerializer; return defaultCookieSerializer;
} }
}
}

@ -1,42 +1,37 @@
package com.tamguo.utils; package com.tamguo.utils;
import java.io.FileInputStream; // 导入文件输入流类 import java.io.FileInputStream;
import java.io.IOException; // 导入输入输出异常类 import java.io.IOException;
import java.security.MessageDigest; // 导入消息摘要类 import java.security.MessageDigest;
import org.apache.commons.codec.binary.Hex; // 导入十六进制编码类 import org.apache.commons.codec.binary.Hex;
/**
* FileMd5Utils MD5
*/
public class FileMd5Utils { public class FileMd5Utils {
/** /**
* MD5 * md5()
* @param fileInputStream * @return md5 value
* @return MD5
*/ */
public static String getMD5(FileInputStream fileInputStream) { public static String getMD5(FileInputStream fileInputStream) {
try { try {
// 获取 MD5 消息摘要实例
MessageDigest MD5 = MessageDigest.getInstance("MD5"); MessageDigest MD5 = MessageDigest.getInstance("MD5");
// 创建字节数组,大小为 8192 字节
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int length; // 定义读取到的字节长度变量 int length;
while ((length = fileInputStream.read(buffer))!= -1) { // 循环读取文件内容 while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length); // 更新消息摘要 MD5.update(buffer, 0, length);
} }
return new String(Hex.encodeHex(MD5.digest())); // 将消息摘要的结果进行十六进制编码并转换为字符串返回 return new String(Hex.encodeHex(MD5.digest()));
} catch (Exception e) { // 捕获异常 } catch (Exception e) {
e.printStackTrace(); // 打印异常信息 e.printStackTrace();
return null; // 返回空值 return null;
} finally { // 无论是否发生异常,都会执行以下代码块 } finally {
try { try {
if (fileInputStream!= null) { // 如果文件输入流不为空 if (fileInputStream != null){
fileInputStream.close(); // 关闭文件输入流 fileInputStream.close();
} }
} catch (IOException e) { // 捕获输入输出异常 } catch (IOException e) {
e.printStackTrace(); // 打印异常信息 e.printStackTrace();
} }
} }
} }
}
}

@ -1,68 +1,43 @@
package com.tamguo.utils; package com.tamguo.utils;
import org.apache.shiro.SecurityUtils; // 导入 Shiro 的安全工具类 import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session; // 导入 Shiro 的会话类 import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject; // 导入 Shiro 的主体类 import org.apache.shiro.subject.Subject;
import com.tamguo.modules.member.model.MemberEntity; // 导入会员实体类
import com.tamguo.modules.member.model.MemberEntity;
/**
* ShiroUtils Shiro
*/
public class ShiroUtils { public class ShiroUtils {
/**
*
*/
public static Session getSession() { public static Session getSession() {
return SecurityUtils.getSubject().getSession(); // 获取 Shiro 主体的会话 return SecurityUtils.getSubject().getSession();
} }
/**
*
*/
public static Subject getSubject() { public static Subject getSubject() {
return SecurityUtils.getSubject(); // 获取 Shiro 主体 return SecurityUtils.getSubject();
} }
/**
*
*/
public static MemberEntity getMember() { public static MemberEntity getMember() {
return (MemberEntity)SecurityUtils.getSubject().getPrincipal(); // 获取 Shiro 主体的主要对象(会员实体) return (MemberEntity)SecurityUtils.getSubject().getPrincipal();
} }
/**
* ID
*/
public static String getMemberId() { public static String getMemberId() {
return getMember().getId(); // 获取会员实体的 ID return getMember().getId();
} }
/**
*
*/
public static void setSessionAttribute(Object key, Object value) { public static void setSessionAttribute(Object key, Object value) {
getSession().setAttribute(key, value); // 在会话中设置属性键值对 getSession().setAttribute(key, value);
} }
/**
*
*/
public static Object getSessionAttribute(Object key) { public static Object getSessionAttribute(Object key) {
return getSession().getAttribute(key); // 获取会话中指定键的属性值 return getSession().getAttribute(key);
} }
/**
*
*/
public static boolean isLogin() { public static boolean isLogin() {
return SecurityUtils.getSubject().getPrincipal()!= null; // 判断 Shiro 主体的主要对象是否不为空 return SecurityUtils.getSubject().getPrincipal() != null;
} }
/**
*
*/
public static void logout() { public static void logout() {
SecurityUtils.getSubject().logout(); // 执行 Shiro 主体的注销操作 SecurityUtils.getSubject().logout();
} }
}
}

@ -18,6 +18,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.tamguo.common.utils.DateUtils; import com.tamguo.common.utils.DateUtils;
@ -28,83 +29,42 @@ import com.tamguo.config.redis.CacheService;
import com.tamguo.modules.member.service.IMemberService; import com.tamguo.modules.member.service.IMemberService;
import com.tamguo.utils.ShiroUtils; import com.tamguo.utils.ShiroUtils;
/**
* AccountController
*/
@Controller @Controller
public class AccountController { public class AccountController {
/**
*
*/
@Value("${file.storage.path}") @Value("${file.storage.path}")
String fileStoragePath; String fileStoragePath;
/**
*
*/
@Value("${tamguo.domain.name}") @Value("${tamguo.domain.name}")
String tamguoDomainName; String tamguoDomainName;
/**
*
*/
@Autowired @Autowired
IMemberService iMemberService; IMemberService iMemberService;
/**
*
*/
@Autowired @Autowired
CacheService cacheService; CacheService cacheService;
/**
*
*/
private static final String AVATOR_NO_FORMAT = "00000"; private static final String AVATOR_NO_FORMAT = "00000";
/**
*
*/
private static final String AVATOR_PREFIX = "MTX"; private static final String AVATOR_PREFIX = "MTX";
/**
* "account.html"
* @param model
* @return
*/
@RequestMapping(value = {"account.html"}, method = RequestMethod.GET) @RequestMapping(value = {"account.html"}, method = RequestMethod.GET)
public ModelAndView list(ModelAndView model) { public ModelAndView list(ModelAndView model) {
model.setViewName("account"); model.setViewName("account");
model.addObject("member", iMemberService.findByUid(ShiroUtils.getMemberId())); model.addObject("member", iMemberService.findByUid(ShiroUtils.getMemberId()));
return model; return model;
} }
/**
*
* @return
*/
@RequestMapping(value = {"getCurrentMember"}, method = RequestMethod.GET) @RequestMapping(value = {"getCurrentMember"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result getCurrentMember() { public Result getCurrentMember() {
return Result.result(0, iMemberService.findByUid(ShiroUtils.getMemberId()), "success"); return Result.result(0, iMemberService.findByUid(ShiroUtils.getMemberId()), "success");
} }
/**
*
* @param file
* @param request HTTP
* @return
* @throws IOException
*/
@RequestMapping(value = "uploadFile", method = RequestMethod.POST) @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public UploaderMessage uploadFileHandler(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException { public UploaderMessage uploadFileHandler(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
if (!file.isEmpty()) { if (!file.isEmpty()) {
InputStream in = null; InputStream in = null;
OutputStream out = null; OutputStream out = null;
try { try {
String path = fileStoragePath + DateUtils.format(new Date(), "yyyyMMdd"); String path = fileStoragePath + DateUtils.format(new Date(), "yyyyMMdd");
File dir = new File(path); File dir = new File(path);
@ -133,12 +93,12 @@ public class AccountController {
msg.setError("File upload file"); msg.setError("File upload file");
return msg; return msg;
} finally { } finally {
if (out!= null) { if (out != null) {
out.close(); out.close();
out = null; out = null;
} }
if (in!= null) { if (in != null) {
in.close(); in.close();
in = null; in = null;
} }
@ -151,10 +111,6 @@ public class AccountController {
} }
} }
/**
*
* @return
*/
private String getAvatorNo() { private String getAvatorNo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String format = sdf.format(new Date()); String format = sdf.format(new Date());
@ -164,4 +120,4 @@ public class AccountController {
String avatorNo = AVATOR_PREFIX + df.format(incr); String avatorNo = AVATOR_PREFIX + df.format(incr);
return avatorNo; return avatorNo;
} }
} }

@ -1,75 +1,63 @@
package com.tamguo.web; package com.tamguo.web;
import java.util.List; import java.util.List;
import org.slf4j.Logger; // 导入日志记录器接口 import org.slf4j.Logger;
import org.slf4j.LoggerFactory; // 导入日志工厂类 import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; // 导入自动注入注解 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; // 导入控制器注解 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 导入请求映射注解 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 导入请求方法注解 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; // 导入响应体注解 import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.tamguo.common.utils.Result;
import com.tamguo.modules.book.model.BookCategoryEntity;
import com.tamguo.modules.book.service.IBookCategoryService;
import com.alibaba.druid.util.StringUtils; // 导入字符串工具类
import com.alibaba.fastjson.JSONArray; // 导入 JSON 数组类
import com.alibaba.fastjson.JSONObject; // 导入 JSON 对象类
import com.baomidou.mybatisplus.mapper.Condition; // 导入条件构建器类
import com.tamguo.modules.book.model.BookCategoryEntity; // 导入图书分类实体类
import com.tamguo.modules.book.service.IBookCategoryService; // 导入图书分类服务接口
/**
* BookCategoryController
*/
@Controller @Controller
public class BookCategoryController { public class BookCategoryController {
private Logger logger = LoggerFactory.getLogger(getClass()); // 创建日志记录器实例 private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
private IBookCategoryService iBookCategoryService; // 自动注入图书分类服务实例 private IBookCategoryService iBookCategoryService;
/**
* POST
* @param parentId ID
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = {"getBookCategory.html"}, method = RequestMethod.POST) @RequestMapping(value = {"getBookCategory.html"}, method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result getBookCategory(String parentId) { public Result getBookCategory(String parentId) {
try { try {
List<BookCategoryEntity> bookCategoryList = null; // 定义图书分类列表变量 List<BookCategoryEntity> bookCategoryList = null;
if(StringUtils.isEmpty(parentId)) { // 如果父分类 ID 为空 if(StringUtils.isEmpty(parentId)) {
bookCategoryList = iBookCategoryService.selectList(Condition.create().eq("parent_id", "0")); // 查询父分类为 0 的图书分类列表 bookCategoryList = iBookCategoryService.selectList(Condition.create().eq("parent_id", "0"));
} else { }else {
bookCategoryList = iBookCategoryService.selectList(Condition.create().eq("parent_id", parentId)); // 查询指定父分类 ID 的图书分类列表 bookCategoryList = iBookCategoryService.selectList(Condition.create().eq("parent_id", parentId));
} }
return Result.successResult(processBookCategoryList(bookCategoryList)); // 返回处理后的图书分类列表结果,并标记为成功 return Result.successResult(processBookCategoryList(bookCategoryList));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录异常日志 logger.error(e.getMessage() , e);
return Result.failResult("查询失败!"); // 返回失败结果及错误信息 return Result.failResult("查询失败!");
} }
} }
/**
* JSON
* @param bookCategoryList
* @return JSON
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private JSONArray processBookCategoryList(List<BookCategoryEntity> bookCategoryList) { private JSONArray processBookCategoryList(List<BookCategoryEntity> bookCategoryList) {
JSONArray entitys = new JSONArray(); // 创建 JSON 数组实例 JSONArray entitys = new JSONArray();
for(int i = 0; i < bookCategoryList.size(); i++) { // 遍历图书分类列表 for(int i=0 ; i<bookCategoryList.size() ; i++) {
BookCategoryEntity bc = bookCategoryList.get(i); // 获取当前图书分类实体 BookCategoryEntity bc = bookCategoryList.get(i);
JSONObject entity = new JSONObject(); // 创建 JSON 对象实例 JSONObject entity = new JSONObject();
entity.put("label", bc.getName()); // 设置标签为分类名称 entity.put("label", bc.getName());
entity.put("value", bc.getId()); // 设置值为分类 ID entity.put("value", bc.getId());
Integer count = iBookCategoryService.selectCount(Condition.create().eq("parent_id", bc.getId())); // 获取当前分类的子分类数量 Integer count = iBookCategoryService.selectCount(Condition.create().eq("parent_id", bc.getId()));
if(count > 0) { if(count > 0) {
entity.put("children", new JSONArray()); // 如果有子分类,设置子分类数组 entity.put("children", new JSONArray());
} }
entitys.add(entity); // 将当前分类对象添加到 JSON 数组中 entitys.add(entity);
} }
return entitys; // 返回处理后的 JSON 数组 return entitys;
} }
} }

@ -28,145 +28,105 @@ import com.tamguo.modules.book.service.IBookService;
import com.tamguo.modules.book.service.IDocumentService; import com.tamguo.modules.book.service.IDocumentService;
import com.tamguo.utils.ShiroUtils; import com.tamguo.utils.ShiroUtils;
/**
* BookController
*/
@Controller @Controller
public class BookController { public class BookController {
private Logger logger = LoggerFactory.getLogger(getClass()); // 创建日志记录器对象 private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
private IBookService iBookService; // 自动注入图书服务 private IBookService iBookService;
@Autowired @Autowired
private IDocumentService iDocumentService; // 自动注入文档服务 private IDocumentService iDocumentService;
/**
*
* @param bookId ID
* @param model
* @return
*/
@RequestMapping(value = "editBook/{bookId}", method = RequestMethod.GET) @RequestMapping(value = "editBook/{bookId}", method = RequestMethod.GET)
public ModelAndView edit(@PathVariable String bookId, ModelAndView model) { public ModelAndView edit(@PathVariable String bookId , ModelAndView model) {
model.setViewName("book/edit"); // 设置视图名称 model.setViewName("book/edit");
model.addObject("bookId", bookId); // 添加图书 ID 到模型中 model.addObject("bookId", bookId);
return model; // 返回模型视图对象 return model;
} }
/**
*
* @param model
* @return
*/
@RequestMapping(value = {"booklist.html"}, method = RequestMethod.GET) @RequestMapping(value = {"booklist.html"}, method = RequestMethod.GET)
public ModelAndView list(ModelAndView model) { public ModelAndView list(ModelAndView model) {
model.setViewName("booklist"); // 设置视图名称 model.setViewName("booklist");
return model; // 返回模型视图对象 return model;
} }
/**
*
* @param id ID
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = "getDocumentList", method = RequestMethod.POST) @RequestMapping(value = "getDocumentList", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result getDocumentList(String id) { public Result getDocumentList(String id) {
Map<String, Object> map = new HashMap<>(); // 创建一个 Map 对象 Map<String, Object> map = new HashMap<>();
try { try {
BookEntity book = iBookService.selectById(id); // 根据图书 ID 获取图书信息 BookEntity book = iBookService.selectById(id);
List<DocumentEntity> documentList = iDocumentService.selectList(Condition.create().eq("book_id", id).eq("status", DocumentStatusEnum.NORMAL.getValue())); // 根据图书 ID 和文档状态获取文档列表 List<DocumentEntity> documentList = iDocumentService.selectList(Condition.create().eq("book_id", id).eq("status", DocumentStatusEnum.NORMAL.getValue()));
map.put("documentList", this.processDocumentList(documentList)); // 处理文档列表并将结果放入 Map 中 map.put("documentList", this.processDocumentList(documentList));
map.put("book", book); // 将图书信息放入 Map 中 map.put("book", book);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e );
return Result.failResult("查询失败"); // 返回查询失败的结果 return Result.failResult("查询失败");
} }
return Result.successResult(map); // 返回查询成功的结果 return Result.successResult(map);
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = {"getBookList.html"}, method = RequestMethod.POST) @RequestMapping(value = {"getBookList.html"}, method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result getBookList() { public Result getBookList() {
try { try {
List<BookEntity> bookList = iBookService.selectList(Condition.create().eq("owner", ShiroUtils.getMemberId()).orderByDesc(Arrays.asList("create_date"))); // 根据当前用户 ID 获取图书列表 List<BookEntity> bookList = iBookService.selectList(Condition.create().eq("owner", ShiroUtils.getMemberId()).orderDesc(Arrays.asList("create_date")));
return Result.successResult(bookList); // 返回图书列表 return Result.successResult(bookList);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e);
return Result.failResult("查询失败!"); // 返回查询失败的结果 return Result.failResult("查询失败!");
} }
} }
/**
*
* @param book
* @return
*/
@RequestMapping(value = {"saveBook"}, method = RequestMethod.POST) @RequestMapping(value = {"saveBook"}, method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result saveBook(@RequestBody BookEntity book) { public Result saveBook(@RequestBody BookEntity book) {
try { try {
book.setOwner(ShiroUtils.getMemberId()); // 设置图书的所有者为当前用户 book.setOwner(ShiroUtils.getMemberId());
book.setCategoryId(StringUtils.join(book.getCategoryIds(), ",")); // 设置图书的分类 ID 为逗号分隔的字符串 book.setCategoryId(StringUtils.join(book.getCategoryIds(), ","));
iBookService.saveBook(book); // 保存图书 iBookService.saveBook(book);
return Result.result(0, null, "保存成功"); // 返回保存成功的结果 return Result.result(0, null, "保存成功");
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e);
return Result.result(1, null, "保存失败"); // 返回保存失败的结果 return Result.result(1, null, "保存失败");
} }
} }
/**
* JSON
* @param documentList
* @return JSON
*/
private JSONArray processDocumentList(List<DocumentEntity> documentList) { private JSONArray processDocumentList(List<DocumentEntity> documentList) {
JSONArray entitys = new JSONArray(); // 创建 JSON 数组对象 JSONArray entitys = new JSONArray();
for (int i = 0; i < documentList.size(); i++) { // 遍历文档列表 for(int i=0 ; i<documentList.size() ; i ++) {
DocumentEntity doc = documentList.get(i); // 获取当前文档 DocumentEntity doc = documentList.get(i);
JSONObject entity = new JSONObject(); // 创建 JSON 对象 JSONObject entity = new JSONObject();
entity.put("id", doc.getId()); // 设置文档 ID entity.put("id", doc.getId());
entity.put("text", doc.getName()); // 设置文档名称 entity.put("text", doc.getName());
entity.put("parent", "0".equals(doc.getParentId())? "#" : doc.getParentId()); // 设置文档的父节点 entity.put("parent", "0".equals(doc.getParentId()) ? "#" : doc.getParentId());
entity.put("identify", doc.getId()); // 设置文档的标识 entity.put("identify", doc.getId());
entity.put("version", doc.getCreateDate().getTime()); // 设置文档的版本 entity.put("version", doc.getCreateDate().getTime());
JSONObject attr = new JSONObject(); // 创建属性对象 JSONObject attr = new JSONObject();
attr.put("is_open", "0".equals(doc.getIsOpen())? false : true); // 设置文档是否展开 attr.put("is_open", "0".equals(doc.getIsOpen()) ? false : true);
entity.put("a_attr", attr); // 设置文档的属性 entity.put("a_attr", attr);
entitys.add(entity);
entitys.add(entity); // 将文档对象添加到 JSON 数组中
} }
return entitys; // 返回 JSON 数组 return entitys;
} }
/** @RequestMapping(value="book/{id}.html" , method=RequestMethod.GET)
*
* @param id ID
* @return
*/
@RequestMapping(value = "book/{id}.html", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result book(@PathVariable String id) { public Result book(@PathVariable String id) {
try { try {
BookEntity book = iBookService.selectById(id); // 根据图书 ID 获取图书信息 BookEntity book = iBookService.selectById(id);
String categoryIds = book.getCategoryId(); // 获取图书的分类 ID 字符串 String categoryIds = book.getCategoryId();
book.setCategoryIds(Arrays.asList(categoryIds.split(","))); // 将分类 ID 字符串转换为列表 book.setCategoryIds(Arrays.asList(categoryIds.split(",")));
// 获取categoryIds
// 获取 categoryIds return Result.result(0, book, "查询成功!");
return Result.result(0, book, "查询成功!"); // 返回查询成功的结果
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e);
return Result.result(1, null, "查询失败!"); // 返回查询失败的结果 return Result.result(1, null, "查询失败!");
} }
} }
} }

@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathPathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@ -35,45 +35,35 @@ import com.tamguo.modules.book.service.IFileEntityService;
import com.tamguo.modules.book.service.IFileUploadService; import com.tamguo.modules.book.service.IFileUploadService;
import com.tamguo.utils.FileMd5Utils; import com.tamguo.utils.FileMd5Utils;
/**
* DocumentController
*/
@Controller @Controller
@RequestMapping(value = "document") @RequestMapping(value="document")
public class DocumentController { public class DocumentController {
private Logger logger = LoggerFactory.getLogger(getClass()); // 创建日志记录器对象 private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
IDocumentService iDocumentService; // 自动注入文档服务 IDocumentService iDocumentService;
@Autowired @Autowired
IFileEntityService iFileEntityService; // 自动注入文件实体服务 IFileEntityService iFileEntityService;
@Autowired @Autowired
IFileUploadService iFileUploadService; // 自动注入文件上传服务 IFileUploadService iFileUploadService;
@Value("${file.storage.path}") @Value("${file.storage.path}")
private String fileStoragePath; // 文件存储路径配置 private String fileStoragePath;
@Value("${tamguo.domain.name}") @Value("${tamguo.domain.name}")
private String domainName; // 域名配置 private String domainName;
/** @SuppressWarnings("unchecked")
* @RequestMapping(value = "{id}" , method = RequestMethod.GET)
* @param id ID
* @return
*/
@RequestMapping(value = "{id}", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result getDocument(@PathVariable String id) { public Result getDocument(@PathVariable String id) {
DocumentEntity document = null; // 定义文档对象 DocumentEntity document = null;
try { try {
document = iDocumentService.selectById(id); // 根据 ID 获取文档信息 document = iDocumentService.selectById(id);
// 查询附件 // 查询附件
List<FileUploadEntity> fileUploads = iFileUploadService.selectList(Condition.create().eq("biz_key", document.getId()).eq("biz_type", BizTypeEnum.DOCUMENT.getValue())); List<FileUploadEntity> fileUploads = iFileUploadService.selectList(Condition.create().eq("biz_key", document.getId()).eq("biz_type", BizTypeEnum.DOCUMENT.getValue()));
if (!CollectionUtils.isEmpty(fileUploads)) { if(!CollectionUtils.isEmpty(fileUploads)) {
for (int i = 0; i < fileUploads.size(); i++) { for(int i=0 ; i<fileUploads.size() ; i++) {
FileUploadEntity fileUpload = fileUploads.get(i); FileUploadEntity fileUpload = fileUploads.get(i);
FileEntity fileEntity = iFileEntityService.selectOne(Condition.create().eq("file_id", fileUpload.getFileId())); FileEntity fileEntity = iFileEntityService.selectOne(Condition.create().eq("file_id", fileUpload.getFileId()));
fileUpload.setFilePath(domainName + "files/" + fileEntity.getFilePath()); fileUpload.setFilePath(domainName + "files/" + fileEntity.getFilePath());
@ -82,172 +72,152 @@ public class DocumentController {
document.setFileUploads(fileUploads); document.setFileUploads(fileUploads);
} }
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e );
return Result.failResult("查询失败"); // 返回查询失败结果 return Result.failResult("查询失败");
} }
return Result.successResult(document); // 返回查询成功结果 return Result.successResult(document);
} }
/** /**
* *
* @param document
* @return
*/ */
@RequestMapping(value = "modify", method = RequestMethod.POST) @RequestMapping(value = "modify" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result modify(DocumentEntity document) { public Result modify(DocumentEntity document) {
try { try {
iDocumentService.modify(document); // 修改文档内容 iDocumentService.modify(document);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e );
return Result.failResult("保存失败"); // 返回保存失败结果 return Result.failResult("保存失败");
} }
return Result.successResult("保存成功"); // 返回保存成功结果 return Result.successResult("保存成功");
} }
/** /**
* *
* @param document
* @return
*/ */
@RequestMapping(value = "create", method = RequestMethod.POST) @RequestMapping(value = "create" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result create(DocumentEntity document) { public Result create(DocumentEntity document) {
try { try {
iDocumentService.create(document); // 创建文档 iDocumentService.create(document);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e );
return Result.failResult("保存失败"); // 返回保存失败结果 return Result.failResult("保存失败");
} }
return Result.successResult(document); // 返回保存成功结果 return Result.successResult(document);
} }
/** @SuppressWarnings("unchecked")
* @RequestMapping(value = "uploadImage" , method = RequestMethod.POST)
* @param file
* @param bookId ID
* @param request HTTP
* @return
*/
@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result uploadImage(@RequestParam("editormd-image-file") MultipartFile file, String bookId, HttpServletRequest request) { public Result uploadImage(@RequestParam("editormd-image-file") MultipartFile file, String bookId , HttpServletRequest request) {
try { try {
String fileMd5 = FileMd5Utils.getMD5((FileInputStream) file.getInputStream()); // 获取文件的 MD5 值 String fileMd5 = FileMd5Utils.getMD5((FileInputStream)file.getInputStream());
FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5)); // 根据 MD5 值查询系统文件 FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5));
if (sysFile!= null) { if(sysFile != null) {
sysFile.setFilePath(domainName + "files/" + sysFile.getFilePath()); sysFile.setFilePath(domainName + "files/" + sysFile.getFilePath());
return Result.successResult(sysFile); // 如果文件已存在,直接返回文件信息 return Result.successResult(sysFile);
} }
String filePath = fileStoragePath + "book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId; // 生成文件存储路径 String filePath = fileStoragePath + "book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId;
File dest = new File(filePath); File dest = new File(filePath);
if (!dest.exists()) { if(!dest.exists()) {
dest.mkdirs(); // 创建存储目录 dest.mkdirs();
} }
// save 文件 // save 文件
FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()), file.getBytes()); // 保存文件 FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()) , file.getBytes());
FileEntity fileEntity = new FileEntity(); // 创建文件实体对象
fileEntity.setFileContentType(file.getContentType()); // 设置文件类型 FileEntity fileEntity = new FileEntity();
fileEntity.setFileExtension(file.getOriginalFilename()); // 设置文件扩展名 fileEntity.setFileContentType(file.getContentType());
fileEntity.setFileMd5(FileMd5Utils.getMD5((FileInputStream) file.getInputStream())); // 设置文件 MD5 值 fileEntity.setFileExtension(file.getOriginalFilename());
fileEntity.setFileSize(file.getSize()); // 设置文件大小 fileEntity.setFileMd5(FileMd5Utils.getMD5((FileInputStream)file.getInputStream()));
fileEntity.setFilePath("book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId + "/" + file.getOriginalFilename()); // 设置文件路径 fileEntity.setFileSize(file.getSize());
iFileEntityService.insert(fileEntity); // 插入文件实体到数据库 fileEntity.setFilePath("book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId + "/" + file.getOriginalFilename());
iFileEntityService.insert(fileEntity);
fileEntity.setFilePath(domainName + "files/" + fileEntity.getFilePath()); // 设置文件路径
fileEntity.setFilePath(domainName + "files/" + fileEntity.getFilePath());
return Result.successResult(fileEntity); // 返回文件信息
return Result.successResult(fileEntity);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Result.failResult("上传失败"); // 如果上传失败,返回失败结果 return Result.failResult("上传失败");
} }
} }
/** /**
* *
* @param file
* @param documentId ID
* @param bookId ID
* @param request HTTP
* @return
*/ */
@RequestMapping(value = "uploadFile", method = RequestMethod.POST) @SuppressWarnings("unchecked")
@RequestMapping(value = "uploadFile" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result uploadFile(@RequestParam("editormd-file-file") MultipartFile file, String documentId, String bookId, HttpServletRequest request) { public Result uploadFile(@RequestParam("editormd-file-file") MultipartFile file , String documentId , String bookId , HttpServletRequest request) {
try { try {
String fileMd5 = FileMd5Utils.getMD5((FileInputStream) file.getInputStream()); // 获取文件的 MD5 值 String fileMd5 = FileMd5Utils.getMD5((FileInputStream)file.getInputStream());
FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5)); // 根据 MD5 值查询系统文件 FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5));
// 文件不存在 // 文件不存在
if (sysFile == null) { if(sysFile == null) {
String filePath = fileStoragePath + "book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId; // 生成文件存储路径 String filePath = fileStoragePath + "book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId;
File dest = new File(filePath); File dest = new File(filePath);
if (!dest.exists()) { if(!dest.exists()) {
dest.mkdirs(); // 创建存储目录 dest.mkdirs();
} }
// save 文件 // save 文件
FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()), file.getBytes()); // 保存文件 FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()) , file.getBytes());
sysFile = new FileEntity(); // 创建文件实体对象 sysFile = new FileEntity();
sysFile.setFileContentType(file.getContentType()); // 设置文件类型 sysFile.setFileContentType(file.getContentType());
sysFile.setFileExtension(file.getOriginalFilename()); // 设置文件扩展名 sysFile.setFileExtension(file.getOriginalFilename());
sysFile.setFileMd5(FileMd5Utils.getMD5((FileInputStream) file.getInputStream())); // 设置文件 MD5 值 sysFile.setFileMd5(FileMd5Utils.getMD5((FileInputStream)file.getInputStream()));
sysFile.setFileSize(file.getSize()); // 设置文件大小 sysFile.setFileSize(file.getSize());
sysFile.setFilePath("book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId + "/" + file.getOriginalFilename()); // 设置文件路径 sysFile.setFilePath("book/" + DateUtil.fomatDate(new Date(), "yyyyMM") + "/" + bookId + "/" + file.getOriginalFilename());
iFileEntityService.insert(sysFile); // 插入文件实体到数据库 iFileEntityService.insert(sysFile);
} }
// 创建上传记录 // 创建上传记录
FileUploadEntity fileUpload = new FileUploadEntity(); // 创建文件上传记录对象 FileUploadEntity fileUpload = new FileUploadEntity();
fileUpload.setBizKey(documentId); // 设置业务键 fileUpload.setBizKey(documentId);
fileUpload.setBizType(BizTypeEnum.DOCUMENT); // 设置业务类型 fileUpload.setBizType(BizTypeEnum.DOCUMENT);
fileUpload.setCreateBy("system"); // 设置创建者 fileUpload.setCreateBy("system");
fileUpload.setCreateDate(new Date()); // 设置创建日期 fileUpload.setCreateDate(new Date());
fileUpload.setFileId(sysFile.getFileId()); // 设置文件 ID fileUpload.setFileId(sysFile.getFileId());
fileUpload.setFileName(sysFile.getFileExtension()); // 设置文件名称 fileUpload.setFileName(sysFile.getFileExtension());
fileUpload.setFileType(file.getContentType()); // 设置文件类型 fileUpload.setFileType(file.getContentType());
fileUpload.setUpdateBy("system"); // 设置更新者 fileUpload.setUpdateBy("system");
fileUpload.setUpdateDate(new Date()); // 设置更新日期 fileUpload.setUpdateDate(new Date());
fileUpload.setStatus(FileUploadStatusEnum.NORMAL); // 设置状态为正常 fileUpload.setStatus(FileUploadStatusEnum.NORMAL);
iFileUploadService.insert(fileUpload); // 插入文件上传记录到数据库 iFileUploadService.insert(fileUpload);
fileUpload.setFilePath(domainName + "files/" + sysFile.getFilePath()); // 设置文件路径 fileUpload.setFilePath(domainName + "files/" + sysFile.getFilePath());
fileUpload.setFileSize(sysFile.getFileSize()); // 设置文件大小 fileUpload.setFileSize(sysFile.getFileSize());
return Result.successResult(fileUpload);
return Result.successResult(fileUpload); // 返回文件上传记录信息
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Result.failResult("上传失败"); // 如果上传失败,返回失败结果 return Result.failResult("上传失败");
} }
} }
/** /**
* *
* @param id ID
* @return
*/ */
@RequestMapping(value = "removeFile", method = RequestMethod.POST) @RequestMapping(value = "removeFile" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result removeFile(String id) { public Result removeFile(String id) {
try { try {
iFileUploadService.deleteById(id); // 根据 ID 删除文件上传记录 iFileUploadService.deleteById(id);
} catch (Exception e) { } catch (Exception e) {
return Result.result(1, null, "删除失败"); // 如果删除失败,返回失败结果 return Result.result(1, null, "删除失败");
} }
return Result.result(0, null, "删除成功"); // 如果删除成功,返回成功结果 return Result.result(0, null, "删除成功");
} }
/** @SuppressWarnings("unchecked")
* @RequestMapping(value="delete" , method = RequestMethod.POST)
* @param id ID
* @return
*/
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result delete(String id) { public Result delete(String id) {
try { try {
DocumentEntity document = iDocumentService.selectById(id); // 根据 ID 获取文档信息 DocumentEntity document = iDocumentService.selectById(id);
iDocumentService.delete(Condition.create().eq("batch_no", document.getBatchNo())); // 根据批次号删除文档 iDocumentService.delete(Condition.create().eq("batch_no", document.getBatchNo()));
} catch (Exception e) { } catch (Exception e) {
return Result.result(1, null, "删除失败"); // 如果删除失败,返回失败结果 return Result.result(1, null, "删除失败");
} }
return Result.result(0, null, "删除成功"); // 如果删除成功,返回成功结果 return Result.result(0, null, "删除成功");
} }
} }

@ -1,45 +1,34 @@
package com.tamguo.web; package com.tamguo.web;
import org.apache.commons.mail.EmailException; // 导入邮件异常类 import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired; // 导入自动注入注解 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; // 标注为控制器类 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 处理请求映射 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 请求方法 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; // 返回响应体 import org.springframework.web.bind.annotation.ResponseBody;
import com.tamguo.common.utils.Result; // 通用结果类 import com.tamguo.common.utils.Result;
import com.tamguo.common.utils.SystemConstant; // 系统常量类 import com.tamguo.common.utils.SystemConstant;
import com.tamguo.modules.sys.service.IEmailService; // 邮件服务接口 import com.tamguo.modules.sys.service.IEmailService;
/**
* EmailController
*/
@Controller @Controller
public class EmailController { public class EmailController {
@Autowired // 自动注入邮件服务实例 @Autowired
private IEmailService iEmailService; private IEmailService iEmailService;
/**
*
* @param email
* @return
*/
@RequestMapping(value = {"sendFindPasswordEmail"}, method = RequestMethod.GET) @RequestMapping(value = {"sendFindPasswordEmail"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result sendFindPasswordEmail(String email) { public Result sendFindPasswordEmail(String email){
try { try {
// 调用邮件服务发送找回密码邮件,并获取结果 Integer result = iEmailService.sendFindPasswordEmail(email , SystemConstant.ALIYUN_MAIL_SUBJECT_FINDPASSWORD);
Integer result = iEmailService.sendFindPasswordEmail(email, SystemConstant.ALIYUN_MAIL_SUBJECT_FINDPASSWORD); if(result == 0){
if (result == 0) {
// 如果结果为 0返回服务器异常的结果
return Result.result(200, null, "服务器异常"); return Result.result(200, null, "服务器异常");
} }
} catch (EmailException e) { } catch (EmailException e) {
// 捕获邮件异常并打印堆栈信息
e.printStackTrace(); e.printStackTrace();
} }
// 无论是否发生异常,都返回服务器异常的结果
return Result.result(500, null, "服务器异常"); return Result.result(500, null, "服务器异常");
} }
}
}

@ -1,81 +1,73 @@
package com.tamguo.web; package com.tamguo.web;
import java.io.File; // 文件类 import java.io.File;
import java.io.FileInputStream; // 文件输入流类 import java.io.FileInputStream;
import java.io.IOException; // 输入输出异常类 import java.io.IOException;
import java.util.Date; // 日期类 import java.util.Date;
import javax.servlet.http.HttpServletRequest; // HTTP 请求类 import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils; // 文件工具类 import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired; // 自动注入注解 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; // 值注入注解 import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; // 控制器类 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 请求映射 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 请求方法 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; // 请求参数 import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; // 返回响应体 import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.mapper.Condition; // 条件类 import com.baomidou.mybatisplus.mapper.Condition;
import com.tamguo.common.utils.DateUtil; // 日期工具类 import com.tamguo.common.utils.DateUtil;
import com.tamguo.common.utils.Result; // 通用结果类 import com.tamguo.common.utils.Result;
import com.tamguo.modules.book.model.FileEntity; // 文件实体类 import com.tamguo.modules.book.model.FileEntity;
import com.tamguo.modules.book.service.IFileEntityService; // 文件服务接口 import com.tamguo.modules.book.service.IFileEntityService;
import com.tamguo.utils.FileMd5Utils;
/**
* FileController
*/
@Controller @Controller
public class FileController { public class FileController {
@Value("${file.storage.path}") // 获取配置文件中文件存储路径的值 @Value("${file.storage.path}")
private String fileStoragePath; private String fileStoragePath;
@Value("${tamguo.domain.name}")
@Value("${tamguo.domain.name}") // 获取配置文件中域名的值
private String domainName; private String domainName;
@Autowired
@Autowired // 自动注入文件服务实例
private IFileEntityService iFileEntityService; private IFileEntityService iFileEntityService;
/**
*
* @param file
* @param request HTTP
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = "uploadImage", method = RequestMethod.POST) @RequestMapping(value = "uploadImage" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) { public Result uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
try { try {
String fileMd5 = FileMd5Utils.getMD5((FileInputStream)file.getInputStream()); // 获取文件的 MD5 值 String fileMd5 = FileMd5Utils.getMD5((FileInputStream)file.getInputStream());
FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5)); // 根据文件 MD5 查找文件实体 FileEntity sysFile = iFileEntityService.selectOne(Condition.create().eq("file_md5", fileMd5));
if (sysFile!= null) { // 如果找到文件实体 if(sysFile != null) {
sysFile.setFilePath(domainName + "files/" + sysFile.getFilePath()); // 设置文件路径 sysFile.setFilePath(domainName + "files/" + sysFile.getFilePath());
return Result.successResult(sysFile); // 返回文件实体 return Result.successResult(sysFile);
} }
String filePath = fileStoragePath + DateUtil.fomatDate(new Date(), "yyyyMM") + "/avatar"; // 设置文件存储路径 String filePath = fileStoragePath + DateUtil.fomatDate(new Date(), "yyyyMM") + "/avatar";
File dest = new File(filePath); // 创建文件对象 File dest = new File(filePath);
if (!dest.exists()) { // 如果文件不存在 if(!dest.exists()) {
dest.mkdirs(); // 创建文件夹 dest.mkdirs();
} }
// 保存文件 // save 文件
FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()), file.getBytes()); FileUtils.writeByteArrayToFile(new File(filePath + "/" + file.getOriginalFilename()) , file.getBytes());
FileEntity fileEntity = new FileEntity(); // 创建文件实体对象 FileEntity fileEntity = new FileEntity();
fileEntity.setFileContentType(file.getContentType()); // 设置文件类型 fileEntity.setFileContentType(file.getContentType());
fileEntity.setFileExtension(file.getOriginalFilename()); // 设置文件扩展名 fileEntity.setFileExtension(file.getOriginalFilename());
fileEntity.setFileMd5(FileMd5Utils.getMD5((FileInputStream)file.getInputStream())); // 设置文件 MD5 值 fileEntity.setFileMd5(FileMd5Utils.getMD5((FileInputStream)file.getInputStream()));
fileEntity.setFileSize(file.getSize()); // 设置文件大小 fileEntity.setFileSize(file.getSize());
fileEntity.setFilePath(DateUtil.fomatDate(new Date(), "yyyyMM") + "/avatar/" + file.getOriginalFilename()); // 设置文件路径 fileEntity.setFilePath(DateUtil.fomatDate(new Date(), "yyyyMM") + "/avatar/" + file.getOriginalFilename());
iFileEntityService.insert(fileEntity); // 插入文件实体到数据库 iFileEntityService.insert(fileEntity);
fileEntity.setFilePath(domainName + "files/" + fileEntity.getFilePath()); // 设置文件路径 fileEntity.setFilePath(domainName + "files/" + fileEntity.getFilePath());
return Result.successResult(fileEntity); // 返回文件实体 return Result.successResult(fileEntity);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); // 打印异常信息 e.printStackTrace();
return Result.failResult("上传失败"); // 返回上传失败的结果 return Result.failResult("上传失败");
} }
} }
}
}

@ -18,108 +18,74 @@ import com.tamguo.modules.book.model.DocumentEntity;
import com.tamguo.modules.book.model.enums.DocumentStatusEnum; import com.tamguo.modules.book.model.enums.DocumentStatusEnum;
import com.tamguo.modules.book.service.IDocumentService; import com.tamguo.modules.book.service.IDocumentService;
/**
* HistoryDocController
*/
@Controller @Controller
@RequestMapping(value="document") @RequestMapping(value="document")
public class HistoryDocController { public class HistoryDocController {
// 日志记录器
private Logger logger = LoggerFactory.getLogger(getClass()); private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
private IDocumentService iDocumentService; private IDocumentService iDocumentService;
/** /**
* *
* @param id ID
* @param model
* @return
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = "history", method = RequestMethod.POST) @RequestMapping(value = "history" , method = RequestMethod.POST)
public ModelAndView history(String id, ModelAndView model) { public ModelAndView history(String id , ModelAndView model) {
model.setViewName("book/history"); // 设置视图名称 model.setViewName("book/history");
// 根据 ID 查询文档实体
DocumentEntity document = iDocumentService.selectById(id); DocumentEntity document = iDocumentService.selectById(id);
model.addObject("document", document); // 添加文档到模型 model.addObject("document", document);
// 查询与该批次号且状态为历史的文档列表,并按创建日期降序排序
model.addObject("historyList", iDocumentService.selectList(Condition.create().eq("batch_no", document.getBatchNo()).eq("status", DocumentStatusEnum.HISTORY.getValue()).orderDesc(Arrays.asList("create_date")))); model.addObject("historyList", iDocumentService.selectList(Condition.create().eq("batch_no", document.getBatchNo()).eq("status", DocumentStatusEnum.HISTORY.getValue()).orderDesc(Arrays.asList("create_date"))));
return model; return model;
} }
/** /**
* *
* @param id ID
* @return
*/ */
@RequestMapping(value = "history/delete", method = RequestMethod.POST) @RequestMapping(value = "history/delete" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result delete(String id) { public Result delete(String id) {
try { try {
// 根据 ID 删除文档
iDocumentService.deleteById(id); iDocumentService.deleteById(id);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e);
return Result.failResult("删除失败!"); // 返回删除失败结果 return Result.failResult("删除失败!");
} }
return Result.successResult("删除成功!"); // 返回删除成功结果 return Result.successResult("删除成功!");
} }
/** /**
* *
* @param id ID
* @return
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = "history/restore", method = RequestMethod.POST) @RequestMapping(value = "history/restore" , method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result restore(String id) { public Result restore(String id) {
try { try {
// 根据 ID 查询历史文档
DocumentEntity history = iDocumentService.selectById(id); DocumentEntity history = iDocumentService.selectById(id);
// 获取历史文档的内容和 markdown
String content = history.getContent(); String content = history.getContent();
String markdown = history.getMarkdown(); String markdown = history.getMarkdown();
// 查询与该批次号且状态为正常的文档
DocumentEntity document = iDocumentService.selectOne(Condition.create().eq("batch_no", history.getBatchNo()).eq("status", DocumentStatusEnum.NORMAL.getValue())); DocumentEntity document = iDocumentService.selectOne(Condition.create().eq("batch_no", history.getBatchNo()).eq("status", DocumentStatusEnum.NORMAL.getValue()));
// 设置文档的内容和 markdown
document.setContent(content); document.setContent(content);
document.setMarkdown(markdown); document.setMarkdown(markdown);
document.setCover("no"); document.setCover("no");
// 修改文档
iDocumentService.modify(document); iDocumentService.modify(document);
return Result.successResult(document); // 返回恢复成功结果和文档 return Result.successResult(document);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); // 记录错误日志 logger.error(e.getMessage() , e);
return Result.failResult("恢复失败!"); // 返回恢复失败结果 return Result.failResult("恢复失败!");
} }
} }
/**
*
* @param id ID
* @param model
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RequestMapping(value = "history/compare/{id}", method = RequestMethod.POST) @RequestMapping(value = "history/compare/{id}" , method = RequestMethod.POST)
public ModelAndView compare(@PathVariable String id, ModelAndView model) { @ResponseBody
model.setViewName("book/compare"); // 设置视图名称 public ModelAndView compare(@PathVariable String id , ModelAndView model) {
model.setViewName("book/compare");
// 根据 ID 查询历史文档
DocumentEntity history = iDocumentService.selectById(id); DocumentEntity history = iDocumentService.selectById(id);
model.addObject("history", history); // 添加历史文档到模型 model.addObject("history", history);
model.addObject("document", iDocumentService.selectOne(Condition.create().eq("status", DocumentStatusEnum.NORMAL.getValue()).eq("batch_no", history.getBatchNo())));
// 查询与该批次号且状态为正常的文档
model.addObject("document", iDocumentService.selectOne(Condition.create().eq("batch_no", history.getBatchNo()).eq("status", DocumentStatusEnum.NORMAL.getValue())));
return model; return model;
} }
} }

@ -1,36 +1,30 @@
package com.tamguo.web; package com.tamguo.web;
import org.springframework.beans.factory.annotation.Autowired; // 注入依赖 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; // 定义为控制器 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 处理请求映射 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 请求方法 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; // 模型和视图 import org.springframework.web.servlet.ModelAndView;
import com.tamguo.modules.member.service.IMemberService;
import com.tamguo.modules.member.service.IMemberService; // 会员服务接口 import com.tamguo.utils.ShiroUtils;
import com.tamguo.utils.ShiroUtils; // Shiro 工具类
/** /**
* - * -
* *
* @author tamguo * @author tamguo
* *
*/ */
@Controller @Controller
public class IndexController { public class IndexController {
@Autowired // 自动注入会员服务实例 @Autowired
IMemberService iMemberService; IMemberService iMemberService;
/** @RequestMapping(value = {"index.html" , "/"}, method = RequestMethod.GET)
* index.html / GET public ModelAndView index(ModelAndView model){
* model.setViewName("index");
* @param model model.addObject("member", iMemberService.selectById(ShiroUtils.getMemberId()));
* @return
*/
@RequestMapping(value = {"index.html", "/"}, method = RequestMethod.GET)
public ModelAndView index(ModelAndView model) {
model.setViewName("index"); // 设置视图名称为 "index"
model.addObject("member", iMemberService.selectById(ShiroUtils.getMemberId())); // 添加会员信息到模型中
return model; return model;
} }
}
}

@ -22,67 +22,32 @@ import com.tamguo.common.utils.Result;
import com.tamguo.common.utils.SystemConstant; import com.tamguo.common.utils.SystemConstant;
import com.tamguo.utils.ShiroUtils; import com.tamguo.utils.ShiroUtils;
/**
*
*
* @author tamguo
*
*/
@Controller @Controller
public class LoginController { public class LoginController {
/**
*
*
* @param response
* @param session
* @throws ServletException Servlet
* @throws IOException IO
*/
@RequestMapping("captcha.jpg") @RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response, HttpSession session) throws ServletException, IOException { public void captcha(HttpServletResponse response , HttpSession session) throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store, no-cache"); response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg"); response.setContentType("image/jpeg");
String a = CaptchaUtils.generateCaptcha(response.getOutputStream()); String a = CaptchaUtils.generateCaptcha(response.getOutputStream());
session.setAttribute(SystemConstant.KAPTCHA_SESSION_KEY, a); session.setAttribute(SystemConstant.KAPTCHA_SESSION_KEY, a);
} }
/**
* GET
*
* @param redirectUrl URL
* @param model
* @return
*/
@RequestMapping(value = "/login.html", method = RequestMethod.GET) @RequestMapping(value = "/login.html", method = RequestMethod.GET)
public ModelAndView login(String redirectUrl, ModelAndView model) { public ModelAndView login(String redirectUrl , ModelAndView model){
model.setViewName("login"); model.setViewName("login");
model.addObject("isVerifyCode", "0"); model.addObject("isVerifyCode" , "0");
model.addObject("redirectUrl", redirectUrl); model.addObject("redirectUrl", redirectUrl);
return model; return model;
} }
/**
* POST
*
* @param username
* @param password
* @param verifyCode
* @param redirectUrl URL
* @param model
* @param session
* @param response
* @return null
* @throws IOException IO
*/
@RequestMapping(value = "/submitLogin.html", method = RequestMethod.POST) @RequestMapping(value = "/submitLogin.html", method = RequestMethod.POST)
public ModelAndView submitLogin(String username, String password, String verifyCode, String redirectUrl, ModelAndView model, HttpSession session, HttpServletResponse response) throws IOException { public ModelAndView submitLogin(String username , String password , String verifyCode , String redirectUrl , ModelAndView model , HttpSession session , HttpServletResponse response) throws IOException{
Result result = Result.successResult(null); Result result = Result.successResult(null);
if(StringUtils.isEmpty(verifyCode)) {
if (StringUtils.isEmpty(verifyCode)) {
result = Result.result(202, null, "请输入验证码"); result = Result.result(202, null, "请输入验证码");
} else if (StringUtils.isNotEmpty(verifyCode)) { } else if(StringUtils.isNotEmpty(verifyCode)){
String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString(); String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString();
if (!verifyCode.equalsIgnoreCase(kaptcha)) { if (!verifyCode.equalsIgnoreCase(kaptcha)) {
result = Result.result(205, null, "验证码错误"); result = Result.result(205, null, "验证码错误");
@ -91,11 +56,11 @@ public class LoginController {
UsernamePasswordToken token = new UsernamePasswordToken(username, password); UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try { try {
subject.login(token); subject.login(token);
session.setAttribute("currMember", ShiroUtils.getMember()); session.setAttribute("currMember", ShiroUtils.getMember());
if (!StringUtils.isEmpty(redirectUrl)) { if(!StringUtils.isEmpty(redirectUrl)) {
response.sendRedirect(redirectUrl); response.sendRedirect(redirectUrl);
} else { }else {
response.sendRedirect("index.html"); response.sendRedirect("index.html");
} }
return null; return null;
@ -105,39 +70,27 @@ public class LoginController {
result = Result.result(202, null, "用户名或密码有误,请重新输入或找回密码"); result = Result.result(202, null, "用户名或密码有误,请重新输入或找回密码");
} catch (LockedAccountException e) { } catch (LockedAccountException e) {
result = Result.result(203, null, "账号被锁定"); result = Result.result(203, null, "账号被锁定");
} }
} }
} }
model.setViewName("login");
model.setViewName("login");
model.addObject("code", result.getCode()); model.addObject("code", result.getCode());
model.addObject("msg", result.getMessage()); model.addObject("msg" , result.getMessage());
model.addObject("username", username); model.addObject("username", username);
return model; return model;
} }
/**
* GET
*
* @param username
* @param password
* @param captcha
* @param model
* @param session
* @return
*/
@RequestMapping(value = "/miniLogin.html", method = RequestMethod.GET) @RequestMapping(value = "/miniLogin.html", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result miniLogin(String username, String password, String captcha, ModelAndView model, HttpSession session) { public Result miniLogin(String username , String password , String captcha, ModelAndView model , HttpSession session) {
Result result = null; Result result = null;
if(StringUtils.isEmpty(captcha)) {
if (StringUtils.isEmpty(captcha)) {
result = Result.result(204, null, "请输入验证码"); result = Result.result(204, null, "请输入验证码");
} else if (StringUtils.isNotEmpty(captcha)) { } else if(StringUtils.isNotEmpty(captcha)){
String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString(); String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString();
if (!captcha.equalsIgnoreCase(kaptcha)) { if (!captcha.equalsIgnoreCase(kaptcha)) {
result = Result.result(205, null, "验证码错误"); result = Result.result(205, null, "验证码错误");
} else { }else {
Subject subject = ShiroUtils.getSubject(); Subject subject = ShiroUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password); UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try { try {
@ -150,23 +103,18 @@ public class LoginController {
result = Result.result(202, null, "用户名或密码有误,请重新输入或找回密码"); result = Result.result(202, null, "用户名或密码有误,请重新输入或找回密码");
} catch (LockedAccountException e) { } catch (LockedAccountException e) {
result = Result.result(203, null, "账号被锁定"); result = Result.result(203, null, "账号被锁定");
} }
} }
} }
return result; return result;
} }
/**
*
*
* @return
*/
@RequestMapping(value = "/isLogin.html", method = RequestMethod.GET) @RequestMapping(value = "/isLogin.html", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result isLogin() { public Result isLogin() {
if (ShiroUtils.isLogin()) { if(ShiroUtils.isLogin()) {
return Result.result(1, null, "已经登录"); return Result.result(1, null , "已经登录");
} }
return Result.result(0, null, "未登录"); return Result.result(0, null, "未登录");
} }
} }

@ -1,27 +1,28 @@
package com.tamguo.web; package com.tamguo.web;
import javax.servlet.http.HttpServletRequest; // 导入 HttpServletRequest 类 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; // 导入 HttpServletResponse 类 import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; // 导入 HttpSession 类 import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller; // 表示这是一个控制器类 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 用于处理请求映射 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 用于指定请求方法 import org.springframework.web.bind.annotation.RequestMethod;
import com.tamguo.utils.ShiroUtils; // 导入 ShiroUtils 类 import com.tamguo.utils.ShiroUtils;
@Controller // 声明这是一个控制器 @Controller
public class LogoutController { public class LogoutController {
/** /**
* *
*/ */
@RequestMapping(value = "logout.html", method = RequestMethod.GET) // 映射到 "logout.html" 且使用 GET 方法的请求 @RequestMapping(value = "logout.html", method = RequestMethod.GET)
public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) { // 接收请求、响应和会话对象 public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
if (session.getAttribute("currMember")!= null) { // 如果会话中当前成员不为空 if (session.getAttribute("currMember") != null) {
session.removeAttribute("currMember"); // 从会话中移除当前成员属性 session.removeAttribute("currMember");
ShiroUtils.logout(); // 执行 ShiroUtils 的注销操作 ShiroUtils.logout();
} }
return "redirect:/"; // 重定向到根路径 return "redirect:/";
} }
}
}

@ -1,95 +1,81 @@
package com.tamguo.web; package com.tamguo.web;
import javax.servlet.http.HttpSession; // 导入 HttpSession 类 import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired; // 表示自动注入 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; // 声明这是一个控制器类 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; // 处理请求映射 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // 指定请求方法 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; // 用于返回响应体 import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; // 模型和视图类 import org.springframework.web.servlet.ModelAndView;
import com.tamguo.common.utils.Result; // 通用结果类 import com.tamguo.common.utils.Result;
import com.tamguo.common.utils.SystemConstant; // 系统常量类 import com.tamguo.common.utils.SystemConstant;
import com.tamguo.modules.member.service.IMemberService; // 会员服务接口 import com.tamguo.modules.member.service.IMemberService;
@Controller // 控制器注解 @Controller
public class PasswordController { public class PasswordController {
@Autowired // 自动注入会员服务 @Autowired
private IMemberService iMemberService; private IMemberService iMemberService;
/**
*
*/
@RequestMapping(value = "password/find.html", method = RequestMethod.GET) @RequestMapping(value = "password/find.html", method = RequestMethod.GET)
public ModelAndView confirmAccount(ModelAndView model) { // 处理方法,接收模型和视图对象 public ModelAndView confirmAccount(ModelAndView model){
model.setViewName("password/confirmAccount"); // 设置视图名称 model.setViewName("password/confirmAccount");
return model; // 返回模型和视图 return model;
} }
/**
*
*/
@RequestMapping(value = "password/confirmAccount.html", method = RequestMethod.POST) @RequestMapping(value = "password/confirmAccount.html", method = RequestMethod.POST)
public ModelAndView submitConfirmAccount(String username, String veritycode, ModelAndView model, HttpSession session) { // 处理方法,接收参数、模型和视图对象、会话对象 public ModelAndView submitConfirmAccount(String username , String veritycode , ModelAndView model , HttpSession session){
Result result = iMemberService.confirmAccount(username, veritycode); // 调用会员服务的确认账号方法 Result result = iMemberService.confirmAccount(username, veritycode);
String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString(); // 获取验证码 String kaptcha = session.getAttribute(SystemConstant.KAPTCHA_SESSION_KEY).toString();
if (!veritycode.equalsIgnoreCase(kaptcha)) { // 比较验证码是否正确 if (!veritycode.equalsIgnoreCase(kaptcha)) {
result = Result.result(202, null, "验证码错误"); // 设置错误结果 result = Result.result(202, null, "验证码错误");
} }
if (result.getCode() == 200) { // 如果结果码为 200 if(result.getCode() == 200){
model.setViewName("password/securityCheck"); // 设置视图名称 model.setViewName("password/securityCheck");
model.addObject("result", result); // 添加结果到模型 model.addObject("result", result);
model.addObject("isEmail", username.contains("@")? "1" : "0"); // 添加是否为邮箱的标识到模型 model.addObject("isEmail", username.contains("@") ? "1" : "0");
} else { }else{
model.setViewName("password/confirmAccount"); // 设置视图名称 model.setViewName("password/confirmAccount");
model.addObject("account", username); // 添加账号到模型 model.addObject("account", username);
model.addObject("username", username); // 添加用户名到模型 model.addObject("username",username);
model.addObject("veritycode", veritycode); // 添加验证码到模型 model.addObject("veritycode", veritycode);
model.addObject("code", result.getCode()); // 添加结果码到模型 model.addObject("code", result.getCode());
} }
return model; // 返回模型和视图 return model;
} }
/**
*
*/
@RequestMapping(value = "password/securityCheck.html", method = RequestMethod.POST) @RequestMapping(value = "password/securityCheck.html", method = RequestMethod.POST)
public ModelAndView securityCheck(String username, String isEmail, String mobileVcode, ModelAndView model) { // 处理方法,接收参数、模型和视图对象 public ModelAndView securityCheck(String username , String isEmail , String mobileVcode , ModelAndView model){
Result result = iMemberService.securityCheck(username, isEmail, mobileVcode); // 调用会员服务的安全检查方法 Result result = iMemberService.securityCheck(username , isEmail , mobileVcode);
if (result.getCode() == 200) { // 如果结果码为 200 if(result.getCode() == 200){
model.addObject("username", username); // 添加用户名到模型 model.addObject("username", username);
model.addObject("resetPasswordKey", result.getResult()); // 添加重置密码键到模型 model.addObject("resetPasswordKey" , result.getResult());
model.setViewName("password/resetPassword"); // 设置视图名称 model.setViewName("password/resetPassword");
} else { }else{
model.addObject("result", result); // 添加结果到模型 model.addObject("result", result);
model.addObject("isEmail", isEmail); // 添加是否为邮箱的标识到模型 model.addObject("isEmail", isEmail);
model.addObject("codeError", "1"); // 添加错误标识到模型 model.addObject("codeError", "1");
model.setViewName("password/securityCheck"); // 设置视图名称 model.setViewName("password/securityCheck");
} }
return model; // 返回模型和视图 return model;
} }
/**
*
*/
@RequestMapping(value = "password/resetPassword.html", method = RequestMethod.POST) @RequestMapping(value = "password/resetPassword.html", method = RequestMethod.POST)
public ModelAndView resetPassword(String resetPasswordKey, String username, String password, String verifypwd, ModelAndView model) { // 处理方法,接收参数、模型和视图对象 public ModelAndView resetPassword(String resetPasswordKey , String username , String password , String verifypwd , ModelAndView model){
Result result = iMemberService.resetPassword(resetPasswordKey, username, password, verifypwd); // 调用会员服务的重置密码方法 Result result = iMemberService.resetPassword(resetPasswordKey , username , password , verifypwd);
if (result.getCode() == 200) { // 如果结果码为 200 if(result.getCode() == 200){
model.setViewName("password/resetPwSuccess"); // 设置视图名称 model.setViewName("password/resetPwSuccess");
} else { }else{
model.setViewName("password/resetPassword"); // 设置视图名称 model.setViewName("password/resetPassword");
} }
return model; // 返回模型和视图 return model;
} }
/**
*
*/
@RequestMapping(value = "password/checkAccount.html", method = RequestMethod.GET) @RequestMapping(value = "password/checkAccount.html", method = RequestMethod.GET)
@ResponseBody // 返回响应体 @ResponseBody
public Result checkAccount(String account) { // 处理方法,接收账号参数 public Result checkAccount(String account){
return iMemberService.checkAccount(account); // 调用会员服务的检查账号方法并返回结果 return iMemberService.checkAccount(account);
} }
}
}

@ -19,74 +19,41 @@ import com.tamguo.modules.member.model.MemberEntity;
import com.tamguo.modules.member.service.IMemberService; import com.tamguo.modules.member.service.IMemberService;
import com.tamguo.utils.ShiroUtils; import com.tamguo.utils.ShiroUtils;
/**
* RegisterController
*/
@Controller @Controller
public class RegisterController { public class RegisterController {
/**
* IMemberService
*/
@Autowired @Autowired
private IMemberService iMemberService; private IMemberService iMemberService;
/**
* /register.html GET
* @param model
* @param session HttpSession
* @return
*/
@RequestMapping(value = "/register.html", method = RequestMethod.GET) @RequestMapping(value = "/register.html", method = RequestMethod.GET)
public ModelAndView register(ModelAndView model, HttpSession session) { public ModelAndView register(ModelAndView model , HttpSession session) {
model.setViewName("register"); model.setViewName("register");
return model; return model;
} }
/**
* /checkUsername.html GET
* @param username
* @return
*/
@RequestMapping(value = "/checkUsername.html", method = RequestMethod.GET) @RequestMapping(value = "/checkUsername.html", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result checkUsername(String username) { public Result checkUsername(String username){
return iMemberService.checkUsername(username); return iMemberService.checkUsername(username);
} }
/**
* /checkMobile.html GET
* @param mobile
* @return
*/
@RequestMapping(value = "/checkMobile.html", method = RequestMethod.GET) @RequestMapping(value = "/checkMobile.html", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result checkMobile(String mobile) { public Result checkMobile(String mobile){
return iMemberService.checkMobile(mobile); return iMemberService.checkMobile(mobile);
} }
/**
* /subRegister POST
* @param member
* @param session HttpSession
* @return
*/
@RequestMapping(value = "/subRegister", method = RequestMethod.POST) @RequestMapping(value = "/subRegister", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Result subRegister(@RequestBody MemberEntity member, HttpSession session) { public Result subRegister(@RequestBody MemberEntity member , HttpSession session){
Result result = iMemberService.register(member); Result result = iMemberService.register(member);
if (result.getCode() == 200) { if(result.getCode() == 200) {
// 获取 Shiro 主体
Subject subject = ShiroUtils.getSubject(); Subject subject = ShiroUtils.getSubject();
// 获取注册成功的会员实体对象
MemberEntity memberEntity = (MemberEntity) result.getResult(); MemberEntity memberEntity = (MemberEntity) result.getResult();
// 创建用户名密码令牌
UsernamePasswordToken token = new UsernamePasswordToken(memberEntity.getUsername(), member.getPassword()); UsernamePasswordToken token = new UsernamePasswordToken(memberEntity.getUsername(), member.getPassword());
try { try {
// 主体登录
subject.login(token); subject.login(token);
// 设置当前会员到会话中
session.setAttribute("currMember", ShiroUtils.getMember()); session.setAttribute("currMember", ShiroUtils.getMember());
} catch (UnknownAccountException e) { } catch (UnknownAccountException e) {
return Result.result(201, null, "用户名或密码有误,请重新输入或找回密码"); return Result.result(201, null, "用户名或密码有误,请重新输入或找回密码");
@ -94,8 +61,9 @@ public class RegisterController {
return Result.result(202, null, "用户名或密码有误,请重新输入或找回密码"); return Result.result(202, null, "用户名或密码有误,请重新输入或找回密码");
} catch (LockedAccountException e) { } catch (LockedAccountException e) {
return Result.result(203, null, "账号被锁定"); return Result.result(203, null, "账号被锁定");
} }
} }
return result; return result;
} }
}
}

@ -10,34 +10,21 @@ import com.aliyuncs.exceptions.ClientException;
import com.tamguo.common.utils.Result; import com.tamguo.common.utils.Result;
import com.tamguo.modules.sys.service.ISmsService; import com.tamguo.modules.sys.service.ISmsService;
/**
* SmsController
*/
@Controller @Controller
public class SmsController { public class SmsController {
/**
* ISmsService
*/
@Autowired @Autowired
private ISmsService iSmsService; ISmsService iSmsService;
/**
* /sendFindPasswordSms GET
* @param mobile
* @return
*/
@RequestMapping(value = {"sendFindPasswordSms"}, method = RequestMethod.GET) @RequestMapping(value = {"sendFindPasswordSms"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Result sendFindPasswordSms(String mobile) { public Result sendFindPasswordSms(String mobile){
try { try {
// 调用 ISmsService 发送找回密码短信,并返回结果
return iSmsService.sendFindPasswordSms(mobile); return iSmsService.sendFindPasswordSms(mobile);
} catch (ClientException e) { } catch (ClientException e) {
// 打印异常信息
e.printStackTrace(); e.printStackTrace();
} }
// 返回错误结果
return Result.result(500, null, ""); return Result.result(500, null, "");
} }
}
}

@ -1,59 +1,55 @@
package com.tamguo.web.interceptor; package com.tamguo.web.interceptor;
import java.net.URLEncoder; // 导入用于编码的类 import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest; // 导入 Http 请求类 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; // 导入 Http 响应类 import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component; // 标记为组件 import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; // 继承的拦截器适配器类 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* MemberInterceptor
*/
@Component @Component
public class MemberInterceptor extends HandlerInterceptorAdapter { // 继承自拦截器适配器 public class MemberInterceptor extends HandlerInterceptorAdapter{
/** "重定向 URL"参数名称 */ /** "重定向URL"参数名称 */
private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl"; // 定义重定向 URL 参数名称 private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl";
/** 默认登录 URL */ /** 默认登录URL */
private static final String DEFAULT_LOGIN_URL = "/login.html"; // 定义默认登录 URL private static final String DEFAULT_LOGIN_URL = "/login.html";
/** 登录 URL */
private String loginUrl = DEFAULT_LOGIN_URL; // 定义登录 URL
/** 登录URL */
private String loginUrl = DEFAULT_LOGIN_URL;
/** /**
* *
* *
* @param request HttpServletRequest * @param request
* @param response HttpServletResponse * HttpServletRequest
* @param handler * @param response
* HttpServletResponse
* @param handler
*
* @return * @return
*/ */
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 重写预处理方法 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object currMember = request.getSession().getAttribute("currMember");
Object currMember = request.getSession().getAttribute("currMember"); // 获取当前会话中的会员对象 if (currMember != null) {
return true;
if (currMember!= null) { // 如果会员对象不为空 } else {
return true; // 返回 true继续执行 String requestType = request.getHeader("X-Requested-With");
} else { // 否则 if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
response.addHeader("loginStatus", "accessDenied");
String requestType = request.getHeader("X-Requested-With"); // 获取请求头中的"X-Requested-With" response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
if (requestType!= null && requestType.equalsIgnoreCase("XMLHttpRequest")) { // 如果是 XMLHttpRequest 请求 } else {
response.addHeader("loginStatus", "accessDenied"); // 在响应头中添加登录状态 if (request.getMethod().equalsIgnoreCase("GET")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN); // 发送禁止访问错误 String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
return false; // 返回 false停止执行 response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, "UTF-8"));
} else { // 否则 } else {
response.sendRedirect(request.getContextPath() + loginUrl);
if (request.getMethod().equalsIgnoreCase("GET")) { // 如果是 GET 请求
String redirectUrl = request.getQueryString()!= null? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI(); // 获取重定向 URL
response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, "UTF-8")); // 发送重定向响应
} else { // 如果是其他请求
response.sendRedirect(request.getContextPath() + loginUrl); // 发送重定向响应
} }
return false; // 返回 false停止执行 return false;
} }
} }
} }
}
}

@ -14,23 +14,19 @@ import redis.clients.jedis.ShardedJedis;
/** /**
* *
* *
*/ */
@Service("cacheService") @Service("cacheService")
public class CacheService { public class CacheService {
// 定义 Redis 键的前缀
private final static String REDIS_PRE_KEY = "TAMGUO:"; private final static String REDIS_PRE_KEY = "TAMGUO:";
// 创建对象序列化工具
private SerializeTranscoder objectSerialize = new ObjectUtil(); private SerializeTranscoder objectSerialize = new ObjectUtil();
@Autowired @Autowired
private RedisXMLConfigure redisXMLConfigure; private RedisXMLConfigure redisXMLConfigure;
/** /**
* *
* * @Title: get @Description: @param @return String @throws
* @param key
* @return
*/ */
public String get(String key) { public String get(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -44,10 +40,8 @@ public class CacheService {
} }
/** /**
* *
* * @Title: set @Description: @param @return void @throws
* @param key
* @param value
*/ */
public void set(String key, String value) { public void set(String key, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -61,11 +55,16 @@ public class CacheService {
} }
/** /**
* *
* * set
* @param key *
* @param value * @param key
* @param time * @param value
* @param time
*
* @description
* @exception @since
* 1.0.0
*/ */
public void set(String key, String value, int time) { public void set(String key, String value, int time) {
key = getPreKey(key); key = getPreKey(key);
@ -80,10 +79,10 @@ public class CacheService {
} }
/** /**
* Redis * redis
* *
* @param key * @param key key
* @param value * @param value
*/ */
public void setObject(String key, Object value) { public void setObject(String key, Object value) {
key = getPreKey(key); key = getPreKey(key);
@ -94,16 +93,16 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* Redis *
* *
* @param key * @param key key
* @param value * @param value
* @param time * @param time
*/ */
public void setObject(String key, Object value, int time) { public void setObject(String key, Object value, int time) {
key = getPreKey(key); key = getPreKey(key);
@ -114,15 +113,15 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* Redis *
* *
* @param key * @param key key
* @return * @return
*/ */
public Object getObject(String key) { public Object getObject(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -142,10 +141,10 @@ public class CacheService {
} }
/** /**
* Redis *
* *
* @param key * @param key key
* @return * @return
*/ */
public boolean deleteObject(String key) { public boolean deleteObject(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -156,16 +155,15 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
return false; return false;
} }
/** /**
* *
* * @Title: isExist @Description: key @param @return boolean
* @param key * @throws
* @return
*/ */
public boolean isExist(String key) { public boolean isExist(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -181,22 +179,10 @@ public class CacheService {
return false; return false;
} }
/**
*
*
* @param key
* @return
*/
public boolean notExist(String key) { public boolean notExist(String key) {
return!isExist(key); return !isExist(key);
} }
/**
*
*
* @param key
* @return
*/
public boolean delete(String key) { public boolean delete(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -212,11 +198,11 @@ public class CacheService {
} }
/** /**
* * redis list value key ()
* *
* @param key * @param key
* @param value * @param value
* @return * @return
*/ */
public long putToListEnd(String key, String value) { public long putToListEnd(String key, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -231,25 +217,28 @@ public class CacheService {
} }
/** /**
* * valuekey,
* *
* @param key * @author zhangxin
* @param value * @param key
* @param seconds * @param value
* @param score * @param seconds
* @return * @param score
* @return long
*/ */
public long addToSortedSetAndExpire(String key, String value, int seconds, double score) { public long addToSortedSetAndExpire(String key, String value, int seconds, double score) {
return addToSortedSet(key, value, seconds, true, score); return addToSortedSet(key, value, seconds, true, score);
} }
/** /**
* * valuekey valuescore
* *
* @param key * @author zhangxin
* @param value * @param key
* @param score * @param value
* @return * @param score
* @return long
*/ */
public double addToSortedSetScore(String key, String value, double score) { public double addToSortedSetScore(String key, String value, double score) {
key = getPreKey(key); key = getPreKey(key);
@ -259,28 +248,47 @@ public class CacheService {
Double zincrby = conn.zincrby(key, score, value); Double zincrby = conn.zincrby(key, score, value);
return zincrby; return zincrby;
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
}
}
/**
* memberScore
* @param key
* @param value
* @return
*/
public Double getMemberScore(String key, String member) {
key = getPreKey(key);
ShardedJedis conn = null;
try {
conn = redisXMLConfigure.getConnection();
Double zscore = conn.zscore(key, member);
return zscore == null ? 0 : zscore;
} finally {
redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* * valuekey,
* *
* @param key * @author zhangxin
* @param value * @param key
* @param score * @param value
* @return * @param score
* @return long
*/ */
public long addToSortedSet(String key, String value, double score) { public long addToSortedSet(String key, String value, double score) {
return addToSortedSet(key, value, -1, false, score); return addToSortedSet(key, value, -1, false, score);
} }
/** /**
* * member
* *
* @param key * @return isExist true
* @param member
* @return
*/ */
public boolean isExistSortedSet(String key, String member) { public boolean isExistSortedSet(String key, String member) {
key = getPreKey(key); key = getPreKey(key);
@ -288,18 +296,16 @@ public class CacheService {
try { try {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
Long zrank = conn.zrank(key, member); Long zrank = conn.zrank(key, member);
return zrank!= null; return zrank != null;
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* * member
* *
* @param key * @return isExist true
* @param member
* @return
*/ */
public boolean delSortedSetMember(String key, String[] member) { public boolean delSortedSetMember(String key, String[] member) {
key = getPreKey(key); key = getPreKey(key);
@ -314,14 +320,9 @@ public class CacheService {
} }
/** /**
* * valuekey, setExpirefalse, seconds
* *
* @param key * @return
* @param value
* @param seconds
* @param setExpire
* @param score
* @return
*/ */
private long addToSortedSet(String key, String value, int seconds, boolean setExpire, double score) { private long addToSortedSet(String key, String value, int seconds, boolean setExpire, double score) {
key = getPreKey(key); key = getPreKey(key);
@ -334,17 +335,19 @@ public class CacheService {
} }
return addNum; return addNum;
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* * score
* *
* @param key * @author zhangxin
* @param pageNo 1 * @param key
* @param pageSize * @param pageNo
* @return * 1
* @param pageSize
* @return Set<String>
*/ */
public Set<String> getSortedSetByPage(String key, int pageNo, int pageSize) { public Set<String> getSortedSetByPage(String key, int pageNo, int pageSize) {
key = getPreKey(key); key = getPreKey(key);
@ -362,17 +365,11 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
return null; return null;
} }
/**
*
*
* @param key
* @return
*/
public List<String> getListHead(String key) { public List<String> getListHead(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -389,12 +386,12 @@ public class CacheService {
} }
/** /**
* Map Redis * map
* *
* @param key * @param key
* @param field Map * @param field map field
* @param value Map * @param value map value
* @return 0 1 * @return if filed exist return 0 else return 1
*/ */
public Long hset(String key, String field, String value) { public Long hset(String key, String field, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -403,17 +400,10 @@ public class CacheService {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.hset(key, field, value); return conn.hset(key, field, value);
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/**
* Map Redis
*
* @param key
* @param values Map
* @return
*/
public String hset(String key, Map<String, String> values) { public String hset(String key, Map<String, String> values) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -421,18 +411,10 @@ public class CacheService {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.hmset(key, values); return conn.hmset(key, values);
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/**
* Map Redis
*
* @param key
* @param values Map
* @param time
* @return
*/
public String hset(String key, Map<String, String> values, int time) { public String hset(String key, Map<String, String> values, int time) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -447,28 +429,28 @@ public class CacheService {
} }
/** /**
* Map * mapfield
* *
* @param key * @param key
* @param field * @param field map field
* @return * @return
*/ */
public String hget(String key, String field) { public String hget(String key, String field) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
try { try {
conn = redisXML Configure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.hget(key, field); return conn.hget(key, field);
} finally { } finally {
redisXML Configure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* key 1 * keystring1
* *
* @param key * @param key
* @return 1 * @return
*/ */
public Long decr(String key) { public Long decr(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -480,30 +462,24 @@ public class CacheService {
redisXMLConfigure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* key 1 * keystring1
* *
* @param key * @param key
* @return 1 * @return
*/ */
public Long incr(String key) { public Long incr(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
try { try {
conn = redisXML Configure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.incr(key); return conn.incr(key);
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/**
* Redis
*
* @param key
* @return
*/
private String getPreKey(String key) { private String getPreKey(String key) {
String temp_pre = redisXMLConfigure.getPreKey(); String temp_pre = redisXMLConfigure.getPreKey();
if (null == temp_pre) { if (null == temp_pre) {
@ -511,4 +487,5 @@ public class CacheService {
} }
return temp_pre + key; return temp_pre + key;
} }
}
}

@ -1,28 +1,13 @@
package com.tamguo.config.redis; package com.tamguo.config.redis;
/**
* PoolConfigBean Redis
*/
public class PoolConfigBean { public class PoolConfigBean {
// 最大活跃连接数
private int max_active; private int max_active;
// 最大空闲连接数
private int max_idle; private int max_idle;
// 最大等待时间(毫秒)
private long max_wait; private long max_wait;
/**
*
*/
public PoolConfigBean() { public PoolConfigBean() {
} }
/**
*
* @param max_active
* @param max_idle
* @param max_wait
*/
public PoolConfigBean(int max_active, int max_idle, long max_wait) { public PoolConfigBean(int max_active, int max_idle, long max_wait) {
super(); super();
this.max_active = max_active; this.max_active = max_active;
@ -30,60 +15,33 @@ public class PoolConfigBean {
this.max_wait = max_wait; this.max_wait = max_wait;
} }
/**
*
* @return
*/
public int getMax_active() { public int getMax_active() {
return max_active; return max_active;
} }
/**
*
* @param max_active
*/
public void setMax_active(int max_active) { public void setMax_active(int max_active) {
this.max_active = max_active; this.max_active = max_active;
} }
/**
*
* @return
*/
public int getMax_idle() { public int getMax_idle() {
return max_idle; return max_idle;
} }
/**
*
* @param max_idle
*/
public void setMax_idle(int max_idle) { public void setMax_idle(int max_idle) {
this.max_idle = max_idle; this.max_idle = max_idle;
} }
/**
*
* @return
*/
public long getMax_wait() { public long getMax_wait() {
return max_wait; return max_wait;
} }
/**
*
* @param max_wait
*/
public void setMax_wait(long max_wait) { public void setMax_wait(long max_wait) {
this.max_wait = max_wait; this.max_wait = max_wait;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return "PoolConfig [max_active=" + max_active + ", max_idle=" + max_idle + ", max_wait=" + max_wait + "]"; return "PoolConfig [max_active=" + max_active + ", max_idle=" + max_idle + ", max_wait=" + max_wait + "]";
} }
}
}

@ -1,26 +1,11 @@
package com.tamguo.config.redis; package com.tamguo.config.redis;
/**
* RedisServerNodeBean Redis
*/
public class RedisServerNodeBean { public class RedisServerNodeBean {
// Redis 服务器的 IP 地址
private String ip; private String ip;
// Redis 服务器的端口号
private int port; private int port;
// 是否需要身份验证
private boolean needAuth; private boolean needAuth;
// 身份验证密码
private String auth; private String auth;
/**
* RedisServerNodeBean
*
* @param ip Redis IP
* @param port Redis
* @param needAuth
* @param auth
*/
public RedisServerNodeBean(String ip, int port, boolean needAuth, String auth) { public RedisServerNodeBean(String ip, int port, boolean needAuth, String auth) {
this.ip = ip; this.ip = ip;
this.port = port; this.port = port;
@ -28,85 +13,41 @@ public class RedisServerNodeBean {
this.auth = auth; this.auth = auth;
} }
/**
* Redis IP
*
* @return Redis IP
*/
public String getIp() { public String getIp() {
return ip; return ip;
} }
/**
* Redis IP
*
* @param ip Redis IP
*/
public void setIp(String ip) { public void setIp(String ip) {
this.ip = ip; this.ip = ip;
} }
/**
* Redis
*
* @return Redis
*/
public int getPort() { public int getPort() {
return port; return port;
} }
/**
* Redis
*
* @param port Redis
*/
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
/**
*
*
* @return
*/
public boolean isNeedAuth() { public boolean isNeedAuth() {
return needAuth; return needAuth;
} }
/**
*
*
* @param needAuth
*/
public void setNeedAuth(boolean needAuth) { public void setNeedAuth(boolean needAuth) {
this.needAuth = needAuth; this.needAuth = needAuth;
} }
/**
*
*
* @return
*/
public String getAuth() { public String getAuth() {
return auth; return auth;
} }
/**
*
*
* @param auth
*/
public void setAuth(String auth) { public void setAuth(String auth) {
this.auth = auth; this.auth = auth;
} }
/**
* toString RedisServerNodeBean
*
* @return RedisServerNodeBean
*/
@Override @Override
public String toString() { public String toString() {
return "RedisServer [ip=" + ip + ", port=" + port + ", needAuth=" + needAuth + ", auth=" + auth + "]"; return "RedisServer [ip=" + ip + ", port=" + port + ", needAuth=" + needAuth + ", auth=" + auth + "]";
} }
}
}

@ -18,187 +18,158 @@ import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.ShardedJedisPool;
/**
* RedisXMLConfigure XML Redis ShardedJedisPool
*/
@Component("redisConfigure") @Component("redisConfigure")
public class RedisXMLConfigure implements InitializingBean { public class RedisXMLConfigure implements InitializingBean {
private static final Logger logger = Logger.getLogger(RedisXMLConfigure.class); // 日志记录器 private static final Logger logger = Logger.getLogger(RedisXMLConfigure.class);
private static String preKey; // Redis 键的前缀 private static String preKey;
private static Document document = null; // XML 文档对象 private static Document document = null;
private ShardedJedisPool shardedJedisPool; // ShardedJedis 连接池 private ShardedJedisPool shardedJedisPool;
/**
*
* XML Redis ShardedJedisPool
* @throws Exception
*/
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
XMLConfiguration xmlConfiguration = new XMLConfiguration(); // 创建 XML 配置对象 XMLConfiguration xmlConfiguration = new XMLConfiguration();
String REDIS_PATH = "redis.xml"; // XML 配置文件路径 String REDIS_PATH = "redis.xml";
InputStream stream = null; // 输入流对象 InputStream stream = null;
try { try {
stream = this.getClass().getClassLoader().getResourceAsStream(REDIS_PATH); // 获取 XML 配置文件的输入流 stream = this.getClass().getClassLoader().getResourceAsStream(REDIS_PATH);
if (stream == null) { // 如果输入流为空 if (stream == null) {
logger.error("load redis.xml failed!!!" + REDIS_PATH); // 记录错误日志 logger.error("load redis.xml failed!!!" + REDIS_PATH);
throw new RuntimeException("load redis.xml failed"); // 抛出运行时异常 throw new RuntimeException("load redis.xml failed");
} }
logger.info("Redis XML config path:" + REDIS_PATH); // 记录日志 logger.info("Redis XML config path:" + REDIS_PATH);
if (xmlConfiguration.readConfigFile(stream)) { // 如果成功读取 XML 配置文件 if (xmlConfiguration.readConfigFile(stream)) {
document = xmlConfiguration.getDocument(); // 获取 XML 文档对象 document = xmlConfiguration.getDocument();
} else { } else {
logger.error("load redis.xml failed!!!"); // 记录错误日志 logger.error("load redis.xml failed!!!");
} }
} finally { } finally {
if (null!= stream) // 如果输入流不为空 if (null != stream)
stream.close(); // 关闭输入流 stream.close();
} }
//初始化参数
// 初始化参数 initPreKey();
initPreKey(); // 初始化 Redis 键的前缀 PoolConfigBean pcb = initPoolConfigBean();
PoolConfigBean pcb = initPoolConfigBean(); // 初始化连接池配置对象 List<RedisServerNodeBean> rsnbs = initRedisServerNodeBeans();
List<RedisServerNodeBean> rsnbs = initRedisServerNodeBeans(); // 初始化 Redis 服务器节点信息列表 //实现shardedJedisPool
// 创建 JedisPoolConfig 对象
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 设置最大空闲连接数 //no maxActive config
jedisPoolConfig.setMaxIdle(pcb.getMax_idle()); jedisPoolConfig.setMaxIdle(pcb.getMax_idle());
// 设置最大等待时间(毫秒)
jedisPoolConfig.setMaxWaitMillis(pcb.getMax_wait()); jedisPoolConfig.setMaxWaitMillis(pcb.getMax_wait());
// 创建 ShardedJedisPool 对象 shardedJedisPool = new ShardedJedisPool(jedisPoolConfig,getJedisShardInfo(rsnbs));
shardedJedisPool = new ShardedJedisPool(jedisPoolConfig, getJedisShardInfo(rsnbs)); if(shardedJedisPool == null){
if (shardedJedisPool == null) { // 如果 ShardedJedisPool 对象为空 throw new RuntimeException("config redis.xml error");
throw new RuntimeException("config redis.xml error"); // 抛出运行时异常
} }
} }
/** /**
* * jedis
* @return
*/ */
private PoolConfigBean initPoolConfigBean() { private PoolConfigBean initPoolConfigBean() {
PoolConfigBean poolConfigBean = new PoolConfigBean(); // 创建连接池配置对象 PoolConfigBean poolConfigBean = new PoolConfigBean();
Element poolElement = (Element) document.getElementsByTagName("pool").item(0); // 获取 pool 元素 Element poolElement = (Element) document.getElementsByTagName("pool").item(0);
int max_active = poolElement.hasAttribute("maxActive") ? Integer.parseInt(poolElement.getAttribute("maxActive")) : -1;
int max_active = poolElement.hasAttribute("maxActive")? Integer.parseInt(poolElement.getAttribute("maxActive")) : -1; // 获取最大活跃连接数 int max_idle = poolElement.hasAttribute("maxIdle") ? Integer.parseInt(poolElement.getAttribute("maxIdle")) : -1;
int max_idle = poolElement.hasAttribute("maxIdle")? Integer.parseInt(poolElement.getAttribute("maxIdle")) : -1; // 获取最大空闲连接数 long max_wait = poolElement.hasAttribute("maxWait") ? Long.parseLong(poolElement.getAttribute("maxWait")) : -1;
long max_wait = poolElement.hasAttribute("maxWait")? Long.parseLong(poolElement.getAttribute("maxWait")) : -1; // 获取最大等待时间(毫秒) poolConfigBean.setMax_active(max_active);
poolConfigBean.setMax_idle(max_idle);
poolConfigBean.setMax_active(max_active); // 设置最大活跃连接数 poolConfigBean.setMax_wait(max_wait);
poolConfigBean.setMax_idle(max_idle); // 设置最大空闲连接数
poolConfigBean.setMax_wait(max_wait); // 设置最大等待时间(毫秒)
return poolConfigBean; return poolConfigBean;
} }
/** /**
* Redis * redisserver
* @return Redis
*/ */
private List<RedisServerNodeBean> initRedisServerNodeBeans() { private List<RedisServerNodeBean> initRedisServerNodeBeans() {
List<RedisServerNodeBean> redisServers = new ArrayList<RedisServerNodeBean>(); // 创建 Redis 服务器节点信息列表 List<RedisServerNodeBean> redisServers = new ArrayList<RedisServerNodeBean>();
NodeList serverElements = document.getElementsByTagName("server");
NodeList serverElements = document.getElementsByTagName("server"); // 获取所有 server 元素 int serverLen = serverElements.getLength();
int serverLen = serverElements.getLength(); // 获取 server 元素的数量 if (serverLen < 1) {
logger.error("redis.servers.server must have one !");
if (serverLen < 1) { // 如果 server 元素的数量小于 1 return null;
logger.error("redis.servers.server must have one!"); // 记录错误日志
return null; // 返回空列表
} }
for (int i = 0; i < serverLen; i++) {
for (int i = 0; i < serverLen; i++) { // 遍历所有 server 元素 Element serverElement = (Element) serverElements.item(i);
Element serverElement = (Element) serverElements.item(i); // 获取当前 server 元素 String temp_ip = serverElement.hasAttribute("ip") ? serverElement.getAttribute("ip") : null;
if (temp_ip == null) {
String temp_ip = serverElement.hasAttribute("ip")? serverElement.getAttribute("ip") : null; // 获取 IP 地址 logger.error("redis.servers.server.ip must be supplied!");
if (temp_ip == null) { // 如果 IP 地址为空 return null;
logger.error("redis.servers.server.ip must be supplied!"); // 记录错误日志
return null; // 返回空列表
} }
String temp_port = serverElement.hasAttribute("port")? serverElement.getAttribute("port") : "6379"; // 获取端口号 String temp_port = serverElement.hasAttribute("port") ? serverElement.getAttribute("port") : "6379";
String temp_needAuth = serverElement.hasAttribute("needAuth")? serverElement.getAttribute("needAuth") : "false"; // 获取是否需要身份验证 String temp_needAuth = serverElement.hasAttribute("needAuth") ? serverElement.getAttribute("needAuth") : "false";
String temp_auth = null; // 身份验证密码 String temp_auth = null;
// need auth
// 需要身份验证
if ("true".equals(temp_needAuth)) { if ("true".equals(temp_needAuth)) {
temp_auth = serverElement.hasAttribute("auth")? serverElement.getAttribute("auth") : null; // 获取身份验证密码 temp_auth = serverElement.hasAttribute("auth") ? serverElement.getAttribute("auth") : null;
if (null == temp_auth) { // 如果身份验证密码为空 if (null == temp_auth) {
logger.error("since needAuth is true, auth must be supplied!"); // 记录错误日志 logger.error("since needAuth is true,auth must be supplied!");
return null; // 返回空列表 return null;
} }
} }
RedisServerNodeBean rs = null; // 创建 Redis 服务器节点对象 RedisServerNodeBean rs = null;
try { try {
rs = new RedisServerNodeBean(temp_ip, Integer.parseInt(temp_port), Boolean.parseBoolean(temp_needAuth), temp_auth); // 创建 Redis 服务器节点对象 rs = new RedisServerNodeBean(temp_ip, Integer.parseInt(temp_port), Boolean.parseBoolean(temp_needAuth), temp_auth);
} catch (NumberFormatException e) { // 如果端口号转换为整数时发生异常 } catch (NumberFormatException e) {
logger.error("port must be a number!\n" + e.getMessage()); // 记录错误日志 logger.error("port must be a number!\n" + e.getMessage());
return null; // 返回空列表 return null;
} }
redisServers.add(rs); // 将 Redis 服务器节点对象添加到列表中 redisServers.add(rs);
} }
return redisServers; return redisServers;
} }
/** /**
* JedisShardInfo * JedisShardInfo
* @param redisServers Redis * @param redisServers
* @return JedisShardInfo * @return
*/ */
private List<JedisShardInfo> getJedisShardInfo(List<RedisServerNodeBean> redisServers) { private List<JedisShardInfo> getJedisShardInfo(List<RedisServerNodeBean> redisServers) {
if (redisServers == null) { // 如果 Redis 服务器节点信息列表为空 if(redisServers == null){
logger.error("redisServers must not be empty null"); // 记录错误日志 logger.error("redisServers must not be empty null");
return null; // 返回空列表 return null;
} }
int serverLen = redisServers.size(); // 获取 Redis 服务器节点的数量 int serverLen = redisServers.size();
if (serverLen < 1) { // 如果 Redis 服务器节点的数量小于 1 if (serverLen < 1) {
logger.error("redisServers must not be empty "); // 记录错误日志 logger.error("redisServers must not be empty ");
return null; // 返回空列表 return null;
} }
List<JedisShardInfo> servers = new ArrayList<JedisShardInfo>(serverLen); // 创建 JedisShardInfo 对象列表 List<JedisShardInfo> servers = new ArrayList<JedisShardInfo>(serverLen);
for (int i = 0; i < serverLen; i++) {
for (int i = 0; i < serverLen; i++) { // 遍历 Redis 服务器节点信息列表 RedisServerNodeBean redisServer = redisServers.get(i);
RedisServerNodeBean redisServer = redisServers.get(i); // 获取当前 Redis 服务器节点对象 JedisShardInfo jedisShardInfo = new JedisShardInfo(redisServer.getIp(), redisServer.getPort());
JedisShardInfo jedisShardInfo = new JedisShardInfo(redisServer.getIp(), redisServer.getPort()); // 创建 JedisShardInfo 对象 if (redisServer.isNeedAuth()) {
if (redisServer.isNeedAuth()) { // 如果需要身份验证 jedisShardInfo.setPassword(redisServer.getAuth());
jedisShardInfo.setPassword(redisServer.getAuth()); // 设置身份验证密码
} }
servers.add(jedisShardInfo); // 将 JedisShardInfo 对象添加到列表中 servers.add(jedisShardInfo);
} }
return servers; return servers;
} }
/** /*
* Redis * rediskey
*/ */
private void initPreKey() { private void initPreKey() {
Element preKeyElement = (Element) document.getElementsByTagName("preKey").item(0); // 获取 preKey 元素 Element preKeyElement = (Element) document.getElementsByTagName("preKey").item(0);
preKey = preKeyElement.hasAttribute("value")? preKeyElement.getAttribute("value") : ""; // 获取前缀值 preKey = preKeyElement.hasAttribute("value") ? preKeyElement.getAttribute("value") : "";
} }
/**
* Redis
* @return Redis
*/
public String getPreKey() { public String getPreKey() {
return preKey; return preKey;
} }
/** /**
* Jedis * jedis
* @return Jedis * @return
*/ */
public ShardedJedis getConnection() { public ShardedJedis getConnection() {
return shardedJedisPool.getResource(); return shardedJedisPool.getResource();
} }
/** /**
* Jedis * jedis
* @param resource Jedis * @param resource
*/ */
public void closeConnection(ShardedJedis resource) { public void closeConnection(ShardedJedis resource) {
resource.close(); resource.close();
} }
}
}

@ -8,35 +8,31 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* BookCategoryEntity
*/
@Data @Data
@TableName(value="b_book_category") @TableName(value="b_book_category")
public class BookCategoryEntity extends Model<BookCategoryEntity> { public class BookCategoryEntity extends Model<BookCategoryEntity>{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; // 分类 ID private String id;
private String parentId; // 父分类 ID private String parentId;
private String parentIds; // 父分类 ID 列表 private String parentIds;
private String treeSort; // 树排序 private String treeSort;
private String treeSorts; // 树排序列表 private String treeSorts;
private String treeLeaf; // 是否叶子节点 private String treeLeaf;
private String treeLevel; // 树层次 private String treeLevel;
private String treeNames; // 树名称 private String treeNames;
private String name; // 分类名称 private String name;
private String seoTitle; // SEO 标题 private String seoTitle;
private String seoKeywords; // SEO 关键词 private String seoKeywords;
private String seoDescription; // SEO 描述 private String seoDescription;
private Date createDate; // 创建日期 private Date createDate;
private Date updateDate; // 更新日期 private Date updateDate;
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -10,39 +10,33 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* BookEntity
*/
@Data @Data
@TableName(value="b_book") @TableName(value="b_book")
public class BookEntity extends Model<BookEntity> { public class BookEntity extends Model<BookEntity>{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; // 书籍 ID private String id;
private String categoryId; // 书籍分类 ID private String categoryId;
private String bookImage; // 书籍图片 private String bookImage;
private String owner; // 书籍所有者 private String owner;
private String name; // 书籍名称 private String name;
private String seoTitle; // SEO 标题 private String seoTitle;
private String seoKeywords; // SEO 关键词 private String seoKeywords;
private String seoDescription; // SEO 描述 private String seoDescription;
private Date createDate; // 创建日期 private Date createDate;
private Date updateDate; // 更新日期 private Date updateDate;
// 定义关联字段
@TableField(exist=false) @TableField(exist=false)
private List<String> categoryIds; // 分类 ID 列表 private List<String> categoryIds;
@TableField(exist=false) @TableField(exist=false)
private String memberName; // 会员名称 private String memberName;
@TableField(exist=false) @TableField(exist=false)
private String categoryName; // 分类名称 private String categoryName;
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
} }

@ -13,51 +13,46 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.tamguo.modules.book.model.enums.DocumentStatusEnum; import com.tamguo.modules.book.model.enums.DocumentStatusEnum;
import lombok.Data; import lombok.Data;
/**
* DocumentEntity
*/
@Data @Data
@TableName(value="b_document") @TableName(value="b_document")
public class DocumentEntity extends Model<DocumentEntity> { public class DocumentEntity extends Model<DocumentEntity>{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; // 文档 ID private String id;
private String batchNo; // 批次号 private String batchNo;
private String parentId; // 父文档 ID private String parentId;
private String bookId; // 所属书籍 ID private String bookId;
private String owner; // 所有者 private String owner;
private String name; // 文档名称 private String name;
@JSONField(serialzeFeatures=SerializerFeature.WriteEnumUsingToString) @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
private DocumentStatusEnum status; // 文档状态 private DocumentStatusEnum status;
@TableField(value="is_open") @TableField(value="is_open")
private String isOpen; // 是否公开 private String isOpen;
private Date createDate; // 创建日期 private Date createDate;
private Date updateDate; // 更新日期 private Date updateDate;
// 定义关联字段 private String content;
private String content; // 文档内容 private String markdown;
private String markdown; // Markdown 内容
@TableField(exist=false) @TableField(exist=false)
private Integer level; // 层级 private Integer level;
@TableField(exist=false) @TableField(exist=false)
private String rootId; // 根文档 ID private String rootId;
@TableField(exist=false) @TableField(exist=false)
private boolean leaf; // 是否叶子节点 private boolean leaf;
@TableField(exist=false) @TableField(exist=false)
private List<DocumentEntity> children; // 子文档列表 private List<DocumentEntity> children;
@TableField(exist=false) @TableField(exist=false)
private String cover; // 封面 private String cover;
@TableField(exist=false) @TableField(exist=false)
private List<FileUploadEntity> fileUploads; // 文件上传列表 private List<FileUploadEntity> fileUploads;
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -4,29 +4,16 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* FileEntity
*/
@Data @Data
@TableName(value="b_file_entity") @TableName(value="b_file_entity")
public class FileEntity { public class FileEntity {
// 文件 ID @TableId("file_id")
@TableId("file_id")
private String fileId; private String fileId;
// 文件 MD5 值
private String fileMd5; private String fileMd5;
// 文件路径
private String filePath; private String filePath;
// 文件类型
private String fileContentType; private String fileContentType;
// 文件扩展名
private String fileExtension; private String fileExtension;
// 文件大小(字节数)
private Long fileSize; private Long fileSize;
} }

@ -12,51 +12,33 @@ import com.tamguo.modules.book.model.enums.BizTypeEnum;
import com.tamguo.modules.book.model.enums.FileUploadStatusEnum; import com.tamguo.modules.book.model.enums.FileUploadStatusEnum;
import lombok.Data; import lombok.Data;
/**
* FileUploadEntity
*/
@Data @Data
@TableName(value="b_file_upload") @TableName(value="b_file_upload")
public class FileUploadEntity extends Model<FileUploadEntity> { public class FileUploadEntity extends Model<FileUploadEntity>{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 文件上传 ID
private String id; private String id;
// 文件 ID
private String fileId; private String fileId;
// 文件名
private String fileName; private String fileName;
// 文件类型
private String fileType; private String fileType;
// 业务键 private String bizKey;
private String bizKey; @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
// 业务类型
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private BizTypeEnum bizType; private BizTypeEnum bizType;
// 文件上传状态 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private FileUploadStatusEnum status; private FileUploadStatusEnum status;
// 创建人
private String createBy; private String createBy;
// 创建日期
private Date createDate; private Date createDate;
// 更新人
private String updateBy; private String updateBy;
// 更新日期
private Date updateDate; private Date updateDate;
// 备注
private String remarks; private String remarks;
// 文件路径(不存在数据库中,通过查询关联表得到)
@TableField(exist=false) @TableField(exist=false)
private String filePath; private String filePath;
// 文件大小(字节数)(不存在数据库中,通过查询关联表得到)
@TableField(exist=false) @TableField(exist=false)
private Long fileSize; private Long fileSize;
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -1,50 +1,32 @@
package com.tamguo.modules.book.model.enums; package com.tamguo.modules.book.model.enums;
import java.io.Serializable; // 导入 Serializable 接口 import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IEnum; // 导入 IEnum 接口 import com.baomidou.mybatisplus.enums.IEnum;
/** /**
* IEnum *
*/ */
public enum BizTypeEnum implements IEnum { public enum BizTypeEnum implements IEnum {
// 文档类型 DOCUMENT("document", "文档");
DOCUMENT("document", "文档");
private String value; // 枚举值 private String value;
private String desc; // 枚举描述 private String desc;
/**
*
* @param value
* @param desc
*/
BizTypeEnum(final String value, final String desc) { BizTypeEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -4,53 +4,30 @@ import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IEnum; import com.baomidou.mybatisplus.enums.IEnum;
/** /**
* *
*/ */
public enum DocumentStatusEnum implements IEnum { public enum DocumentStatusEnum implements IEnum {
/** NORMAL("normal", "正常"),
* HISTORY("history", "历史版本");
*/
NORMAL("normal", "正常"),
/**
*
*/
HISTORY("history", "历史版本");
private String value; // 状态值 private String value;
private String desc; // 状态描述 private String desc;
/**
*
* @param value
* @param desc
*/
DocumentStatusEnum(final String value, final String desc) { DocumentStatusEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -4,53 +4,30 @@ import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IEnum; import com.baomidou.mybatisplus.enums.IEnum;
/** /**
* *
*/ */
public enum FileUploadStatusEnum implements IEnum { public enum FileUploadStatusEnum implements IEnum {
/** NORMAL("normal", "正常"),
* DELETE("delete", "删除");
*/
NORMAL("normal", "正常"),
/**
*
*/
DELETE("delete", "删除");
private String value; // 状态值 private String value;
private String desc; // 状态描述 private String desc;
/**
*
* @param value
* @param desc
*/
FileUploadStatusEnum(final String value, final String desc) { FileUploadStatusEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -11,30 +11,22 @@ import com.tamguo.modules.book.dao.BookMapper;
import com.tamguo.modules.book.model.BookEntity; import com.tamguo.modules.book.model.BookEntity;
import com.tamguo.modules.book.service.IBookService; import com.tamguo.modules.book.service.IBookService;
/**
* BookServiceImpl IBookService
*/
@Service(value="bbookServiceImpl") @Service(value="bbookServiceImpl")
public class BookServiceImpl extends ServiceImpl<BookMapper, BookEntity> implements IBookService { public class BookServiceImpl extends ServiceImpl<BookMapper, BookEntity> implements IBookService{
/**
*
*
* @param book
*/
@Transactional(readOnly=false) @Transactional(readOnly=false)
@Override @Override
public void saveBook(BookEntity book) { public void saveBook(BookEntity book) {
book.setCreateDate(new Date()); // 设置创建日期为当前日期 book.setCreateDate(new Date());
book.setUpdateDate(new Date()); // 设置更新日期为当前日期 book.setUpdateDate(new Date());
book.setSeoDescription(book.getName()); // 设置 SEO 描述为书籍名称 book.setSeoDescription(book.getName());
book.setSeoKeywords(book.getName()); // 设置 SEO 关键词为书籍名称 book.setSeoKeywords(book.getName());
book.setSeoTitle(book.getName()); // 设置 SEO 标题为书籍名称 book.setSeoTitle(book.getName());
if(StringUtils.isEmpty(book.getId())) {
if (StringUtils.isEmpty(book.getId())) { // 如果书籍 ID 为空 this.insert(book);
this.insert(book); // 执行插入操作 }else {
} else { this.updateById(book);
this.updateById(book); // 执行更新操作
} }
} }
}
}

@ -12,23 +12,14 @@ import com.tamguo.modules.book.model.DocumentEntity;
import com.tamguo.modules.book.model.enums.DocumentStatusEnum; import com.tamguo.modules.book.model.enums.DocumentStatusEnum;
import com.tamguo.modules.book.service.IDocumentService; import com.tamguo.modules.book.service.IDocumentService;
/**
* DocumentServiceImpl IDocumentService
*/
@Service @Service
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEntity> implements IDocumentService { public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEntity> implements IDocumentService{
/** @Transactional(readOnly=false)
*
*
* @param document
*/
@Transactional(readOnly = false)
@Override @Override
public void modify(DocumentEntity document) { public void modify(DocumentEntity document) {
DocumentEntity entity = this.selectById(document.getId()); // 根据 ID 获取文档实体 DocumentEntity entity = this.selectById(document.getId());
if("yes".equals(document.getCover())) {
if ("yes".equals(document.getCover())) {
// 覆盖修改 // 覆盖修改
entity.setContent(document.getContent()); entity.setContent(document.getContent());
entity.setMarkdown(document.getMarkdown()); entity.setMarkdown(document.getMarkdown());
@ -37,51 +28,47 @@ public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEnt
} else { } else {
String content = entity.getContent(); String content = entity.getContent();
String markdown = entity.getMarkdown(); String markdown = entity.getMarkdown();
// 更新内容 // 更新内容
entity.setContent(document.getContent()); entity.setContent(document.getContent());
entity.setMarkdown(document.getMarkdown()); entity.setMarkdown(document.getMarkdown());
this.updateById(entity); this.updateById(entity);
// 新增历史 // 新增历史
Document.setId(null); document.setId(null);
Document.setContent(content); document.setContent(content);
Document.setMarkdown(markdown); document.setMarkdown(markdown);
Document.setBookId(entity.getBookId()); document.setBookId(entity.getBookId());
Document.setCreateDate(new Date()); document.setCreateDate(new Date());
Document.setIsOpen(entity.getIsOpen()); document.setIsOpen(entity.getIsOpen());
Document.setName(entity.getName()); document.setName(entity.getName());
Document.setOwner(entity.getOwner()); document.setOwner(entity.getOwner());
Document.setParentId(entity.getParentId()); document.setParentId(entity.getParentId());
Document.setUpdateDate(new Date()); document.setUpdateDate(new Date());
Document.setStatus(DocumentStatusEnum.HISTORY); document.setStatus(DocumentStatusEnum.HISTORY);
Document.setBatchNo(entity.getBatchNo()); document.setBatchNo(entity.getBatchNo());
this.insert(document); this.insert(document);
} }
} }
/**
*
*
* @param document
*/
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
@Transactional(readOnly = false) @Transactional(readOnly=false)
@Override @Override
public void create(DocumentEntity document) { public void create(DocumentEntity document) {
if (StringUtils.isEmpty(document.getId())) { if(StringUtils.isEmpty(document.getId())) {
// 如果文档 ID 为空
document.setStatus(DocumentStatusEnum.NORMAL); document.setStatus(DocumentStatusEnum.NORMAL);
document.setCreateDate(new Date()); document.setCreateDate(new Date());
document.setUpdateDate(new Date()); document.setUpdateDate(new Date());
document.setOwner("system"); document.setOwner("system");
document.setBatchNo(new com.baomidou.mybatisplus.toolkit.IdWorker().getIdStr()); document.setBatchNo(new com.baomidou.mybatisplus.toolkit.IdWorker().getIdStr());
this.insert(document); this.insert(document);
} else { }else {
DocumentEntity entity = this.selectById(document.getId()); DocumentEntity entity = this.selectById(document.getId());
entity.setName(document.getName()); entity.setName(document.getName());
entity.setIsOpen(document.getIsOpen()); entity.setIsOpen(document.getIsOpen());
this.updateById(entity); this.updateById(entity);
} }
} }
}
}

@ -9,44 +9,27 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.tamguo.config.dao.SuperEntity; import com.tamguo.config.dao.SuperEntity;
import lombok.Data; import lombok.Data;
/**
* MemberEntity
*/
@Data @Data
@TableName(value="t_member") @TableName(value="t_member")
public class MemberEntity extends SuperEntity<MemberEntity> implements Serializable { public class MemberEntity extends SuperEntity<MemberEntity> implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 用户名
private String username; private String username;
// 昵称
private String nickName; private String nickName;
// 密码
private String password; private String password;
// 头像
private String avatar; private String avatar;
// 手机号
private String mobile; private String mobile;
// 邮箱
private String email; private String email;
// 积分
private Integer point; private Integer point;
// 余额
private BigDecimal amount; private BigDecimal amount;
// 最后登录时间
private Date lastLoginTime; private Date lastLoginTime;
// 发布文章数
private Integer paperNum; private Integer paperNum;
// 提问数
private Integer questionNum; private Integer questionNum;
// 下载数
private Integer downNum; private Integer downNum;
// 点击数
private Integer hitsNum; private Integer hitsNum;
// 验证码(数据库中不存在该字段)
@TableField(exist=false) @TableField(exist=false)
private String verifyCode; private String verifyCode;
// 当前密码(数据库中不存在该字段)
@TableField(exist=false) @TableField(exist=false)
private String nowPassword; private String nowPassword;
} }

@ -1,99 +1,43 @@
package com.tamguo.modules.member.model.condition; package com.tamguo.modules.member.model.condition;
/**
* MemberCondition
*/
public class MemberCondition { public class MemberCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 手机号码
private String mobile; private String mobile;
// 用户名
private String username; private String username;
// 昵称
private String nickName; private String nickName;
/**
*
* @return
*/
public String getMobile() { public String getMobile() {
return mobile; return mobile;
} }
/**
*
* @param mobile
*/
public void setMobile(String mobile) { public void setMobile(String mobile) {
this.mobile = mobile; this.mobile = mobile;
} }
/**
*
* @return
*/
public String getUsername() { public String getUsername() {
return username; return username;
} }
/**
*
* @param username
*/
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/**
*
* @return
*/
public String getNickName() { public String getNickName() {
return nickName; return nickName;
} }
/**
*
* @param nickName
*/
public void setNickName(String nickName) { public void setNickName(String nickName) {
this.nickName = nickName; this.nickName = nickName;
} }
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
}
}

@ -239,532 +239,49 @@ public class MemberService extends ServiceImpl<MemberMapper, MemberEntity> imple
if(!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) { if(!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) {
return Result.result(501, null, "旧密码错误!"); return Result.result(501, null, "旧密码错误!");
} }
package com.tamguo.modules.member.service.impl; if(!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())){
return Result.result(502, null, "验证码错误");
import java.math.BigDecimal; }
import java.util.Date; entity.setPassword(new Sha256Hash(member.getNowPassword()).toHex());
import java.util.List; return Result.result(0, null, "修改成功");
import java.util.UUID; }
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tamguo.common.utils.Result;
import com.tamguo.common.utils.SystemConstant;
import com.tamguo.config.redis.CacheService;
import com.tamguo.modules.book.model.BookEntity;
import com.tamguo.modules.book.service.IBookService;
import com.tamguo.modules.member.dao.MemberMapper;
import com.tamguo.modules.member.model.MemberEntity;
import com.tamguo.modules.member.model.condition.MemberCondition;
import com.tamguo.modules.member.service.IMemberService;
import com.tamguo.modules.sys.service.ISmsService;
/**
* MemberServiceImpl IMemberService
*/
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity> implements IMemberService {
// 注入 MemberMapper
@Autowired
private MemberMapper memberMapper;
// 注入 CacheService
@Autowired
private CacheService cacheService;
// 注入 ISmsService
@Autowired
private ISmsService iSmsService;
// 注入 IBookService
@Autowired
private IBookService iBookService;
/**
*
*
* @param username
* @param password
* @return
*/
@Override
public Result login(String username, String password) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户不存在
if (member == null) {
// 返回错误结果,提示用户名 或 password 有误
return Result.result(201, member, "用户名或密码有误,请重新输入或找回密码");
}
// 获取该用户的登录失败次数
Integer loginFailureCount = this.getLoginFailureCount(member);
// 如果密码错误
if (!new Sha256Hash(password).toHex().equals(member.getPassword())) {
// 登录失败次数加 1
loginFailureCount++;
// 更新登录失败次数
this.updateLoginFailureCount(member, loginFailureCount);
// 返回错误结果,提示用户名 或 password 有误
return Result.result(202, member, "用户名或密码有误,请重新输入或找回密码");
}
// 更新登录失败次数为 0
this.updateLoginFailureCount(member, 0);
// 返回正确结果,提示登录成功
return Result.result(200, member, "登录成功");
}
/**
*
*
* @param member
* @param loginFailureCount
*/
public void updateLoginFailureCount(MemberEntity member, Integer loginFailureCount) {
// 将登录失败次数存储到缓存中key 为 LOGIN_FAILURE_COUNT + member.getId()
cacheService.setObject(SystemConstant.LOGIN_FAILURE_COUNT + member.getId(), loginFailureCount, 2 * 60 * 60);
}
/**
*
*
* @param member
* @return
*/
public Integer getLoginFailureCount(MemberEntity member) {
// 如果 member 为空
if (member == null) {
// 返回 0
return 0;
}
// 如果缓存中不存在登录失败次数
if (!cacheService.isExist(SystemConstant.LOGIN_FAILURE_COUNT + member.getId())) {
// 返回 0
return 0;
}
// 从缓存中获取登录失败次数
return (Integer) cacheService.getObject(SystemConstant.LOGIN_FAILURE_COUNT + member.getId());
}
/**
*
*
* @param username
* @return
*/
@Override
public Result checkUsername(String username) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户存在
if (member!= null) {
// 返回错误结果,提示该用户名已经存在
return Result.result(201, null, "该用户名已经存在");
}
// 返回正确结果,提示该用户名可用
return Result.result(200, null, "该用户名可用");
}
/**
*
*
* @param mobile
* @return
*/
@Override
public Result checkMobile(String mobile) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置手机号
condition.setMobile(mobile);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户存在
if (member!= null) {
// 返回错误结果,提示该手机号已经存在
return Result.result(201, null, "该手机号已经存在");
}
// 返回正确结果,提示该手机号可用
return Result.result(200, null, "该手机号可用");
}
/**
*
*
* @param member
* @return
*/
@Transactional(readOnly = false)
@Override
public Result register(MemberEntity member) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(member.getUsername());
// 从数据库中查询该用户
MemberEntity m = memberMapper.selectOne(condition);
// 如果用户已存在
if (m!= null) {
// 返回错误结果,提示该用户已经存在
return Result.result(201, null, "该用户已经存在");
}
// 创建 MemberEntity 对象
condition = new MemberEntity();
// 设置手机号
condition.setMobile(member.getMobile());
// 从数据库中查询该用户
m = memberMapper.selectOne(condition);
// 如果手机号已存在
if (m!= null) {
// 返回错误结果,提示该手机号已经存在
return Result.result(202, null, "该手机号已经存在");
}
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())) {
// 返回错误结果,提示验证码错误
return Result.result(203, null, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile());
// 如果验证码错误
if (!code.equals(member.getVerifyCode())) {
// 返回错误结果,提示验证码错误
return Result.result(204, null, "验证码错误");
}
// 创建 MemberEntity 对象
MemberEntity entity = new MemberEntity();
// 设置头像
entity.setAvatar(SystemConstant.DEFAULT_MEMBER_AVATAR);
// 设置手机号
entity.setMobile(member.getMobile());
// 设置密码
entity.setPassword(new Sha256Hash(member.getPassword()).toHex());
// 设置用户名
entity.setUsername(member.getUsername());
// 设置昵称
entity.setNickName(member.getUsername());
// 设置邮箱
entity.setEmail(member.getEmail());
// 插入会员信息
memberMapper.insert(entity);
// 返回正确结果,提示注册成功
return Result.result(200, entity, "注册成功");
}
/**
*
*
* @param account
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Result checkAccount(String account) {
// 如果帐号为空
if (StringUtils.isEmpty(account)) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据帐号查询会员信息
query.eq("user_name", account).or().eq("mobile", account);
// 从数据库中查询会员信息
List<MemberEntity> members = memberMapper.selectList(query);
// 如果没有查询到会员信息
if (members.size() == 0) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 返回正确结果,提示帐号存在,并返回会员信息
return Result.result(200, members.get(0), "该帐号存在");
}
/**
*
*
* @param account
* @param veritycode
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Result confirmAccount(String account, String veritycode) {
// 如果帐号为空
if (StringUtils.isEmpty(account)) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据帐号查询会员信息
query.eq("username", account).or().eq("mobile", account);
// 从数据库中查询会员信息
List<MemberEntity> members = memberMapper.selectList(query);
// 如果没有查询到会员信息
if (members.size() == 0) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 返回正确结果,提示帐号存在,并返回会员信息
return Result.result(200, members.get(0), "该帐号存在");
}
/**
*
*
* @param username
* @param isEmail
* @param vcode
* @return
*/
@Override
public Result securityCheck(String username, String isEmail, String vcode) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户不存在
if (member == null) {
// 返回错误结果,提示用户不存在
return Result.result(201, member, "用户不存在");
}
// 如果是邮箱验证
if ("1".equals(isEmail)) {
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MAIL_FIND_PASSWORD_PREFIX + member.getEmail())) {
// 返回错误结果,提示验证码错误
return Result.result(201, member, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MAIL_FIND_PASSWORD_PREFIX + member.getEmail());
// 如果验证码错误
if (!code.equals(vcode)) {
// 返回错误结果,提示验证码错误
return Result.result(202, member, "验证码错误");
}
} else {
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())) {
// 返回错误结果,提示验证码错误
return Result.result(203, member, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile());
// 如果验证码错误
if (!code.equals(vcode)) {
// 返回错误结果,提示验证码错误
return Result.result(204, member, "验证码错误");
}
}
// 创建随机字符串
String key = UUID.randomUUID().toString();
// 将用户名存储到缓存中key 为 SECURITY_CHECK_PREFIX + key
cacheService.setObject(SystemConstant.SECURITY_CHECK_PREFIX + key, username, 2 * 60 * 60);
// 返回正确结果,提示安全验证通过,并返回随机字符串
return Result.result(200, key, "安全验证通过");
}
/**
*
*
* @param resetPasswordKey key
* @param username
* @param password
* @param verifypwd
* @return
*/
@Override
public Result resetPassword(String resetPasswordKey, String username, String password, String verifypwd) {
// 如果缓存中存在重置密码 key
if (cacheService.isExist(SystemConstant.SECURITY_CHECK_PREFIX + resetPasswordKey)) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果密码和确认密码不一致
if (!password.equals(verifypwd)) {
// 返回错误结果,提示密码不一致
return Result.result(201, null, "密码不一致");
}
// 设置密码
member.setPassword(new Sha256Hash(password).toHex());
// 更新会员信息
memberMapper.updateById(member);
}
// 返回正确结果,提示更新成功
return Result.result(200, null, "更新成功");
}
/**
*
*
* @param member
*/
@Transactional(readOnly = false)
@Override
public void updateMember(MemberEntity member) {
// 获取会员信息
MemberEntity entity = memberMapper.selectById(member.getId());
// 设置头像
entity.setAvatar(member.getAvatar());
// 设置邮箱
entity.setEmail(member.getEmail());
// 设置手机号
entity.setMobile(member.getMobile());
// 设置昵称
entity.setNickName(member.getNickName());
// 更新会员信息
memberMapper.updateById(entity);
}
/**
* uid
*
* @param uid uid
* @return
*/
@Transactional(readOnly = true)
@Override
public MemberEntity findByUid(String uid) {
// 根据 uid 查询会员信息
return memberMapper.selectById(uid);
}
/**
*
*
* @param username
* @return
*/
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
@Override
public MemberEntity findByUsername(String username) {
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据用户名查询会员信息
query.eq("username", username).or().eq("mobile", username).or().eq("email", username);
// 从数据库中查询会员信息
return this.selectOne(query);
}
/**
*
*
* @param uid uid
*/
@Transactional(readOnly = false)
@Override
public void updateLastLoginTime(String uid) {
// 获取会员信息
MemberEntity member = memberMapper.selectById(uid);
// 设置最后登录时间为当前时间
member.setLastLoginTime(new Date());
// 更新会员信息
memberMapper.updateById(member);
}
/**
*
*
* @param id id
* @return
*/
@Override
public MemberEntity findCurrMember(String id) {
// 获取会员信息
MemberEntity member = memberMapper.selectById(id);
// 将密码设置为 null
member.setPassword(null);
// 返回会员信息
return member;
}
/**
*
*
* @param member
* @return
*/
@Transactional(readOnly = false)
@Override
public Result updatePwd(MemberEntity member) {
// 获取会员信息
MemberEntity entity = memberMapper.selectById(member.getId());
// 如果旧密码错误
if (!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) {
// 返回错误结果,提示旧密码错误
return Result.result(501, null, "旧密码错误!");
}
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())){
// 如果缓存服务中不存在指定的验证码前缀与会员手机号的组合
return Result.result(502, null, "验证码错误");
}
entity.setPassword(new Sha256Hash(member.getNowPassword()).toHex());
// 设置实体的密码为会员当前密码的 Sha256 哈希值的十六进制表示
return Result.result(0, null, "修改成功");
}
@SuppressWarnings("unchecked")
@Transactional(readOnly=true)
@Override
public Page<MemberEntity> listData(MemberCondition condition) {
// 创建分页对象
Page<MemberEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize());
Condition query = Condition.create();
// 如果条件中的手机号不为空
if(!StringUtils.isEmpty(condition.getMobile())) {
query.eq("mobile", condition.getMobile());
}
// 如果条件中的昵称不为空
if(!StringUtils.isEmpty(condition.getNickName())) {
query.like("nick_name", condition.getNickName());
}
// 如果条件中的用户名不为空
if(!StringUtils.isEmpty(condition.getUsername())) {
query.eq("username", condition.getUsername());
}
return this.selectPage(page, query);
}
@Transactional(readOnly=false)
@Override
public void reward(String id,String bookId, Integer rewardPoint, BigDecimal rewardMoney) {
MemberEntity member = memberMapper.selectById(id);
// 获取会员实体
// 更新会员的积分和金额
member.setPoint(member.getPoint() + rewardPoint);
member.setAmount(member.getAmount().add(rewardMoney));
this.updateById(member);
BookEntity book = iBookService.selectById(bookId); @SuppressWarnings("unchecked")
// 获取书籍实体 @Transactional(readOnly=true)
@Override
public Page<MemberEntity> listData(MemberCondition condition) {
Page<MemberEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize());
Condition query = Condition.create();
if(!StringUtils.isEmpty(condition.getMobile())) {
query.eq("mobile", condition.getMobile());
}
if(!StringUtils.isEmpty(condition.getNickName())) {
query.like("nick_name", condition.getNickName());
}
if(!StringUtils.isEmpty(condition.getUsername())) {
query.eq("username", condition.getUsername());
}
return this.selectPage(page, query);
}
// 发送短信 @Transactional(readOnly=false)
try { @Override
iSmsService.sendRewardSms(member.getMobile(), member.getUsername(), book.getName(), rewardPoint, rewardMoney); public void reward(String id ,String bookId , Integer rewardPoint, BigDecimal rewardMoney) {
} catch (ClientException e) { MemberEntity member = memberMapper.selectById(id);
e.printStackTrace();
} // 更新记录
} member.setPoint(member.getPoint() + rewardPoint);
member.setAmount(member.getAmount().add(rewardMoney));
this.updateById(member);
BookEntity book = iBookService.selectById(bookId);
// 发送短信
try {
iSmsService.sendRewardSms(member.getMobile(), member.getUsername(), book.getName(), rewardPoint, rewardMoney);
} catch (ClientException e) {
e.printStackTrace();
}
}
}

@ -14,67 +14,48 @@ import com.baomidou.mybatisplus.enums.FieldFill;
import com.tamguo.modules.sys.model.enums.SysAreaStatusEnum; import com.tamguo.modules.sys.model.enums.SysAreaStatusEnum;
import lombok.Data; import lombok.Data;
/** /**
* SysAreaEntity * The persistent class for the sys_area database table.
*
*/ */
@Data @Data
@TableName(value = "sys_area") @TableName(value="sys_area")
public class SysAreaEntity implements Serializable { public class SysAreaEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 根区域编码
public static final String ROOT_AREA_CODE = "0"; public static final String ROOT_AREA_CODE = "0";
// 区域编码分隔符
public static final String TREE_CODE_AREA_SEPARATE = ","; public static final String TREE_CODE_AREA_SEPARATE = ",";
// 区域名称分隔符
public static final String TREE_NAME_AREA_SEPARATE = "/"; public static final String TREE_NAME_AREA_SEPARATE = "/";
// 区域编码
@TableId @TableId
private String areaCode; private String areaCode;
// 区域名称
private String areaName; private String areaName;
// 区域类型
private String areaType; private String areaType;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 父区域编码
private String parentCode; private String parentCode;
// 父区域编码列表
private String parentCodes; private String parentCodes;
// 备注
private String remarks; private String remarks;
// 区域状态枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysAreaStatusEnum status; private SysAreaStatusEnum status;
// 是否为叶子节点
private Boolean treeLeaf; private Boolean treeLeaf;
// 树层次
private BigDecimal treeLevel; private BigDecimal treeLevel;
// 树名称
private String treeNames; private String treeNames;
// 树排序
private BigDecimal treeSort; private BigDecimal treeSort;
// 树排序字符串
private String treeSorts; private String treeSorts;
// 更新人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate; private Date updateDate;
// 子区域列表 @TableField(exist=false)
@TableField(exist = false)
private List<SysAreaEntity> children; private List<SysAreaEntity> children;
// 获取区域编码
public String getId() { public String getId() {
return areaCode; return areaCode;
} }

@ -11,72 +11,44 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.FieldFill;
import lombok.Data; import lombok.Data;
/**
* SysCompanyEntity
*/
@Data @Data
@TableName(value = "sys_company") @TableName(value="sys_company")
@KeySequence @KeySequence
public class SysCompanyEntity implements Serializable { public class SysCompanyEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 根公司编码
public static final String ROOT_COMPANY_CODE = "0"; public static final String ROOT_COMPANY_CODE = "0";
// 公司编码分隔符
public static final String TREE_CODE_COMPANY_SEPARATE = ","; public static final String TREE_CODE_COMPANY_SEPARATE = ",";
// 公司名称分隔符
public static final String TREE_NAME_COMPANY_SEPARATE = "/"; public static final String TREE_NAME_COMPANY_SEPARATE = "/";
// 公司编码
@TableId @TableId
private String companyCode; private String companyCode;
// 区域编码
private String areaCode; private String areaCode;
// 公司名称
private String companyName; private String companyName;
// 企业编码
private String corpCode; private String corpCode;
// 企业名称
private String corpName; private String corpName;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 公司全称
private String fullName; private String fullName;
// 父公司编码
private String parentCode; private String parentCode;
// 父公司编码列表
private String parentCodes; private String parentCodes;
// 备注
private String remarks; private String remarks;
// 公司状态
private String status; private String status;
// 是否为叶子节点
private Boolean treeLeaf; private Boolean treeLeaf;
// 树层次
private BigDecimal treeLevel; private BigDecimal treeLevel;
// 树名称
private String treeNames; private String treeNames;
// 树排序
private String treeSort; private String treeSort;
// 树排序字符串
private String treeSorts; private String treeSorts;
// 更新人
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private Date updateDate; private Date updateDate;
// 视图编码
private String viewCode; private String viewCode;
// 树区域名称 @TableField(exist=false)
@TableField(exist = false)
private String treeAreaNames; private String treeAreaNames;
// 获取公司编码
public String getId() { public String getId() {
return companyCode; return companyCode;
} }

@ -13,79 +13,48 @@ import com.baomidou.mybatisplus.enums.FieldFill;
import com.tamguo.modules.sys.model.enums.SysMenuStatusEnum; import com.tamguo.modules.sys.model.enums.SysMenuStatusEnum;
import lombok.Data; import lombok.Data;
/**
* SysMenuEntity
*/
@Data @Data
@TableName(value = "sys_menu") @TableName(value="sys_menu")
public class SysMenuEntity implements Serializable { public class SysMenuEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 根菜单编码
public static final String ROOT_MENU_CODE = "0"; public static final String ROOT_MENU_CODE = "0";
// 菜单编码分隔符
public static final String TREE_CODE_MENU_SEPARATE = ","; public static final String TREE_CODE_MENU_SEPARATE = ",";
// 菜单名称分隔符
public static final String TREE_NAME_MENU_SEPARATE = "/"; public static final String TREE_NAME_MENU_SEPARATE = "/";
// 菜单编码
@TableId @TableId
private String menuCode; private String menuCode;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 是否显示
private String isShow; private String isShow;
// 菜单颜色
private String menuColor; private String menuColor;
// 菜单链接
private String menuHref; private String menuHref;
// 菜单图标
private String menuIcon; private String menuIcon;
// 菜单名称
private String menuName; private String menuName;
// 菜单目标
private String menuTarget; private String menuTarget;
// 菜单类型
private String menuType; private String menuType;
// 父菜单编码
private String parentCode; private String parentCode;
// 父菜单编码列表
private String parentCodes; private String parentCodes;
// 权限
private String permission; private String permission;
// 备注
private String remarks; private String remarks;
// 菜单状态枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysMenuStatusEnum status; private SysMenuStatusEnum status;
// 系统编码
private String sysCode; private String sysCode;
// 是否为叶子节点
private Boolean treeLeaf; private Boolean treeLeaf;
// 树层次
private BigDecimal treeLevel; private BigDecimal treeLevel;
// 树名称
private String treeNames; private String treeNames;
// 树排序
private BigDecimal treeSort; private BigDecimal treeSort;
// 树排序字符串
private String treeSorts; private String treeSorts;
// 更新人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate; private Date updateDate;
// 权重
private BigDecimal weight; private BigDecimal weight;
// 获取菜单编码 public String getId() {
public String getId() { return menuCode;
return menuCode; }
}
} }

@ -10,79 +10,53 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.FieldFill;
import lombok.Data; import lombok.Data;
/** /**
* SysOfficeEntity * The persistent class for the sys_office database table.
*
*/ */
@Data @Data
@TableName(value = "sys_office") @TableName(value="sys_office")
public class SysOfficeEntity implements Serializable { public class SysOfficeEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 根部门编码
public static final String ROOT_OFFICE_CODE = "0"; public static final String ROOT_OFFICE_CODE = "0";
// 部门编码分隔符
public static final String TREE_CODE_OFFICE_SEPARATE = ","; public static final String TREE_CODE_OFFICE_SEPARATE = ",";
// 部门名称分隔符
public static final String TREE_NAME_OFFICE_SEPARATE = "/"; public static final String TREE_NAME_OFFICE_SEPARATE = "/";
// 部门编码
@TableId @TableId
private String officeCode; private String officeCode;
// 地址
private String address; private String address;
// 企业编码
private String corpCode; private String corpCode;
// 企业名称
private String corpName; private String corpName;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 邮箱
private String email; private String email;
// 部门全称
private String fullName; private String fullName;
// 负责人
private String leader; private String leader;
// 部门名称
private String officeName; private String officeName;
// 部门类型
private String officeType; private String officeType;
// 父部门编码
private String parentCode; private String parentCode;
// 父部门编码列表
private String parentCodes; private String parentCodes;
// 电话
private String phone; private String phone;
// 备注
private String remarks; private String remarks;
// 部门状态
private String status; private String status;
// 是否为叶子节点
private Boolean treeLeaf; private Boolean treeLeaf;
// 树层次
private BigDecimal treeLevel; private BigDecimal treeLevel;
// 树名称
private String treeNames; private String treeNames;
// 树排序
private BigDecimal treeSort; private BigDecimal treeSort;
// 树排序字符串
private String treeSorts; private String treeSorts;
// 更新人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate; private Date updateDate;
// 视图编码
private String viewCode; private String viewCode;
// 邮政编码
private String zipCode; private String zipCode;
// grid tree // grid tree
// 获取部门编码
public String getId() { public String getId() {
return this.getOfficeCode(); return this.getOfficeCode();
} }
} }

@ -14,52 +14,34 @@ import com.baomidou.mybatisplus.enums.FieldFill;
import com.tamguo.modules.sys.model.enums.SysPostStatusEnum; import com.tamguo.modules.sys.model.enums.SysPostStatusEnum;
import lombok.Data; import lombok.Data;
/**
* SysPostEntity
*/
@Data @Data
@TableName(value = "sys_post") @TableName(value="sys_post")
public class SysPostEntity extends Model<SysPostEntity> implements Serializable { public class SysPostEntity extends Model<SysPostEntity> implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 岗位编码
@TableId @TableId
private String postCode; private String postCode;
// 企业编码
private String corpCode; private String corpCode;
// 企业名称
private String corpName; private String corpName;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 岗位名称
private String postName; private String postName;
// 岗位排序
private BigDecimal postSort; private BigDecimal postSort;
// 岗位类型
private String postType; private String postType;
// 备注
private String remarks; private String remarks;
// 岗位状态枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysPostStatusEnum status; private SysPostStatusEnum status;
// 更新人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate; private Date updateDate;
/**
* pkVal
* @return
*/
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getPostCode(); return getPostCode();
} }
} }

@ -17,139 +17,87 @@ import com.tamguo.modules.sys.model.enums.SysUserStatusEnum;
import com.tamguo.modules.sys.model.enums.SysUserTypeEnum; import com.tamguo.modules.sys.model.enums.SysUserTypeEnum;
import lombok.Data; import lombok.Data;
/**
* SysUserEntity
*/
@Data @Data
@TableName(value = "sys_user") @TableName(value="sys_user")
public class SysUserEntity extends Model<SysUserEntity> implements Serializable { public class SysUserEntity extends Model<SysUserEntity> implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 用户编码
@TableId @TableId
private String userCode; private String userCode;
// 部门编码
private String officeCode; private String officeCode;
// 部门名称
private String officeName; private String officeName;
// 公司编码
private String companyCode; private String companyCode;
// 公司名称
private String companyName; private String companyName;
// 头像
private String avatar; private String avatar;
// 企业编码
private String corpCode; private String corpCode;
// 企业名称
private String corpName; private String corpName;
// 创建人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String createBy; private String createBy;
// 创建时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date createDate; private Date createDate;
// 邮箱
private String email; private String email;
// 冻结原因
private String freezeCause; private String freezeCause;
// 冻结日期
private Date freezeDate; private Date freezeDate;
// 最后登录日期
private Date lastLoginDate; private Date lastLoginDate;
// 最后登录 IP
private String lastLoginIp; private String lastLoginIp;
// 登录账号
private String loginCode; private String loginCode;
// 用户管理类型枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysUserMgrTypeEnum mgrType; private SysUserMgrTypeEnum mgrType;
// 手机号
private String mobile; private String mobile;
// 手机 IMEI 码
private String mobileImei; private String mobileImei;
// 密码
private String password; private String password;
// 电话
private String phone; private String phone;
// 密码问题更新日期
private Date pwdQuestUpdateDate; private Date pwdQuestUpdateDate;
// 密码问题
private String pwdQuestion; private String pwdQuestion;
// 第二个密码问题 @TableField(value="pwd_question_2")
@TableField(value = "pwd_question_2")
private String pwdQuestion2; private String pwdQuestion2;
// 第三个密码问题 @TableField(value="pwd_question_3")
@TableField(value = "pwd_question_3")
private String pwdQuestion3; private String pwdQuestion3;
// 密码问题答案
private String pwdQuestionAnswer; private String pwdQuestionAnswer;
// 第二个密码问题答案 @TableField(value="pwd_question_answer_2")
@TableField(value = "pwd_question_answer_2")
private String pwdQuestionAnswer2; private String pwdQuestionAnswer2;
// 第三个密码问题答案 @TableField(value="pwd_question_answer_3")
@TableField(value = "pwd_question_answer_3")
private String pwdQuestionAnswer3; private String pwdQuestionAnswer3;
// 密码安全级别
private BigDecimal pwdSecurityLevel; private BigDecimal pwdSecurityLevel;
// 密码更新日期
private Date pwdUpdateDate; private Date pwdUpdateDate;
// 密码更新记录
private String pwdUpdateRecord; private String pwdUpdateRecord;
// 推荐码
private String refCode; private String refCode;
// 推荐人名称
private String refName; private String refName;
// 备注
private String remarks; private String remarks;
// 性别
private String sex; private String sex;
// 个性签名
private String sign; private String sign;
// 用户状态枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysUserStatusEnum status; private SysUserStatusEnum status;
// 更新人
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy; private String updateBy;
// 更新时间
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate; private Date updateDate;
// 用户名
private String userName; private String userName;
// 员工姓名
private String empName; private String empName;
// 用户类型枚举 @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private SysUserTypeEnum userType; private SysUserTypeEnum userType;
// 用户权重
private BigDecimal userWeight; private BigDecimal userWeight;
// 微信 OpenID
private String wxOpenid; private String wxOpenid;
// 英文名
private String userNameEn; private String userNameEn;
// 员工岗位列表(不存在数据库字段) @TableField(exist=false)
@TableField(exist = false)
private List<String> employeePosts; private List<String> employeePosts;
// 用户角色字符串(不存在数据库字段) @TableField(exist=false)
@TableField(exist = false)
private String userRoleString; private String userRoleString;
// 用户数据范围列表 JSON 字符串(不存在数据库字段) @TableField(exist=false)
@TableField(exist = false)
private String userDataScopeListJson; private String userDataScopeListJson;
/**
* pkVal
* @return
*/
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getUserCode(); return getUserCode();
} }
} }

@ -1,316 +1,128 @@
package com.tamguo.modules.sys.model.condition; package com.tamguo.modules.sys.model.condition;
/**
* SysUserCondition
*/
public class SysUserCondition { public class SysUserCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 登录账号
private String loginCode; private String loginCode;
// 用户名
private String userName; private String userName;
// 邮箱
private String email; private String email;
// 手机号
private String mobile; private String mobile;
// 电话号码
private String phone; private String phone;
// 推荐人名称
private String refName; private String refName;
// 部门名称
private String officeName; private String officeName;
// 部门编码
private String officeCode; private String officeCode;
// 公司编码
private String companyCode; private String companyCode;
// 公司名称
private String companyName; private String companyName;
// 岗位编码
private String postCode; private String postCode;
// 用户状态
private String status; private String status;
// 用户类型
private String userType; private String userType;
// 管理类型
private String mgrType; private String mgrType;
// 排序字段
private String orderBy; private String orderBy;
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
/**
*
* @return
*/
public String getLoginCode() { public String getLoginCode() {
return loginCode; return loginCode;
} }
/**
*
* @param loginCode
*/
public void setLoginCode(String loginCode) { public void setLoginCode(String loginCode) {
this.loginCode = loginCode; this.loginCode = loginCode;
} }
/**
*
* @return
*/
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
/**
*
* @param userName
*/
public void setUserName(String userName) { public void setUserName(String userName) {
this.userName = userName; this.userName = userName;
} }
/**
*
* @return
*/
public String getEmail() { public String getEmail() {
return email; return email;
} }
/**
*
* @param email
*/
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/**
*
* @return
*/
public String getMobile() { public String getMobile() {
return mobile; return mobile;
} }
/**
*
* @param mobile
*/
public void setMobile(String mobile) { public void setMobile(String mobile) {
this.mobile = mobile; this.mobile = mobile;
} }
/**
*
* @return
*/
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
/**
*
* @param phone
*/
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
/**
*
* @return
*/
public String getRefName() { public String getRefName() {
return refName; return refName;
} }
/**
*
* @param refName
*/
public void setRefName(String refName) { public void setRefName(String refName) {
this.refName = refName; this.refName = refName;
} }
/**
*
* @return
*/
public String getOfficeName() { public String getOfficeName() {
return officeName; return officeName;
} }
/**
*
* @param officeName
*/
public void setOfficeName(String officeName) { public void setOfficeName(String officeName) {
this.officeName = officeName; this.officeName = officeName;
} }
/**
*
* @return
*/
public String getOfficeCode() { public String getOfficeCode() {
return officeCode; return officeCode;
} }
/**
*
* @param officeCode
*/
public void setOfficeCode(String officeCode) { public void setOfficeCode(String officeCode) {
this.officeCode = officeCode; this.officeCode = officeCode;
} }
/**
*
* @return
*/
public String getCompanyCode() { public String getCompanyCode() {
return companyCode; return companyCode;
} }
/**
*
* @param companyCode
*/
public void setCompanyCode(String companyCode) { public void setCompanyCode(String companyCode) {
this.companyCode = companyCode; this.companyCode = companyCode;
} }
/**
*
* @return
*/
public String getCompanyName() { public String getCompanyName() {
return companyName; return companyName;
} }
/**
*
* @param companyName
*/
public void setCompanyName(String companyName) { public void setCompanyName(String companyName) {
this.companyName = companyName; this.companyName = companyName;
} }
/**
*
* @return
*/
public String getPostCode() { public String getPostCode() {
return postCode; return postCode;
} }
/**
*
* @param postCode
*/
public void setPostCode(String postCode) { public void setPostCode(String postCode) {
this.postCode = postCode; this.postCode = postCode;
} }
/**
*
* @return
*/
public String getStatus() { public String getStatus() {
return status; return status;
} }
/**
*
* @param status
*/
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
/**
*
* @return
*/
public String getUserType() { public String getUserType() {
return userType; return userType;
} }
/**
*
* @param userType
*/
public void setUserType(String userType) { public void setUserType(String userType) {
this.userType = userType; this.userType = userType;
} }
/**
*
* @return
*/
public String getOrderBy() { public String getOrderBy() {
return orderBy; return orderBy;
} }
/**
*
* @param orderBy
*/
public void setOrderBy(String orderBy) { public void setOrderBy(String orderBy) {
this.orderBy = orderBy; this.orderBy = orderBy;
} }
/**
*
* @return
*/
public String getMgrType() { public String getMgrType() {
return mgrType; return mgrType;
} }
/**
*
* @param mgrType
*/
public void setMgrType(String mgrType) { public void setMgrType(String mgrType) {
this.mgrType = mgrType; this.mgrType = mgrType;
} }
}
}

@ -2,40 +2,45 @@ package com.tamguo.modules.tiku.model;
import java.io.Serializable; import java.io.Serializable;
import com.alibaba.fastjson.annotation.JSONField; // 用于 JSON 序列化时的注解 import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature; // JSON 序列化特性 import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.annotations.TableField; // 与数据库表字段相关的注解 import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName; // 表名注解 import com.baomidou.mybatisplus.annotations.TableName;
import com.tamguo.config.dao.SuperEntity; // 父类实体 import com.tamguo.config.dao.SuperEntity;
import com.tamguo.modules.tiku.model.enums.ChapterStatusEnum; // 章节状态枚举 import com.tamguo.modules.tiku.model.enums.ChapterStatusEnum;
import lombok.Data; // Lombok 的数据注解 import lombok.Data;
/** import java.util.List;
* t_chapter
*/
@TableName(value = "t_chapter") // 指定表名为 t_chapter
@Data // Lombok 的数据注解,自动生成 getter 和 setter 等方法
public class ChapterEntity extends SuperEntity<ChapterEntity> implements Serializable { // 继承父类实体,实现序列化接口
private static final long serialVersionUID = 1L; // 序列化版本号
private String courseId; // 课程 ID
private String bookId; // 书籍 ID
private String name; // 章节名称
private String parentCode; // 父章节代码
private String parentCodes; // 父章节代码列表
private Integer questionNum; // 问题数量
private Integer pointNum; // 知识点数量
private Integer orders; // 排序序号
private Boolean treeLeaf; // 是否为叶子节点
private Integer treeLevel; // 树的层级
private String seoTitle; // SEO 标题 /**
private String seoKeywords; // SEO 关键字 * The persistent class for the t_chapter database table.
private String seoDescription; // SEO 描述 *
*/
@TableName(value="t_chapter")
@Data
public class ChapterEntity extends SuperEntity<ChapterEntity> implements Serializable {
private static final long serialVersionUID = 1L;
@TableField(exist = false) // 表示该字段在数据库中不存在 private String courseId;
private List<ChapterEntity> childChapterList; // 子章节列表 private String bookId;
private String name;
private String parentCode;
private String parentCodes;
private Integer questionNum;
private Integer pointNum;
private Integer orders;
private Boolean treeLeaf;
private Integer treeLevel;
private String seoTitle;
private String seoKeywords;
private String seoDescription;
@TableField(exist=false)
private List<ChapterEntity> childChapterList;
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
private ChapterStatusEnum status;
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString) // 指定 JSON 序列化枚举时的特性
private ChapterStatusEnum status; // 章节状态枚举
} }

@ -1,42 +1,43 @@
package com.tamguo.modules.tiku.model; package com.tamguo.modules.tiku.model;
import java.util.Date; // 日期类 import java.util.Date;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.tamguo.modules.tiku.model.enums.CourseStatusEnum;
import lombok.Data;
import com.alibaba.fastjson.annotation.JSONField; // 用于 JSON 序列化时的注解 @Data
import com.alibaba.fastjson.serializer.SerializerFeature; // JSON 序列化特性 @TableName(value="t_course")
import com.baomidou.mybatisplus.annotations.TableField; // 与数据库表字段相关的注解
import com.baomidou.mybatisplus.annotations.TableId; // 表主键注解
import com.baomidou.mybatisplus.annotations.TableName; // 表名注解
import com.baomidou.mybatisplus.enums.FieldFill; // 字段填充策略枚举
import com.tamguo.modules.tiku.model.enums.CourseStatusEnum; // 课程状态枚举
import lombok.Data; // Lombok 的数据注解
@Data // Lombok 的数据注解,自动生成 getter 和 setter 等方法
@TableName(value = "t_course") // 指定表名为 t_course
public class CourseEntity { public class CourseEntity {
@TableId // 标识为主键
private String id; // 课程 ID @TableId
private String subjectId; // 科目 ID private String id;
private String name; // 课程名称 private String subjectId;
private Integer sort; // 排序号 private String name;
private Integer questionNum; // 问题数量 private Integer sort;
private Integer pointNum; // 知识点数量 private Integer questionNum;
private String remarks; // 备注 private Integer pointNum;
private String icon; // 图标 private String remarks;
private String icon;
private String seoTitle; // SEO 标题
private String seoKeywords; // SEO 关键字 private String seoTitle;
private String seoDescription; // SEO 描述 private String seoKeywords;
private String seoDescription;
@TableField(fill = FieldFill.INSERT_UPDATE) // 字段填充策略,在插入和更新时填充
private String createBy; // 创建人 @TableField(fill = FieldFill.INSERT_UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE) // 字段填充策略,在插入和更新时填充 private String createBy;
private String updateBy; // 更新人 @TableField(fill = FieldFill.INSERT_UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE) // 字段填充策略,在插入和更新时填充 private String updateBy;
private Date createDate; // 创建日期 @TableField(fill = FieldFill.INSERT_UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE) // 字段填充策略,在插入和更新时填充 private Date createDate;
private Date updateDate; // 更新日期 @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate;
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
private CourseStatusEnum status;
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString) // 指定 JSON 序列化枚举时的特性 }
private CourseStatusEnum status; // 课程状态枚举
}

@ -1,117 +1,50 @@
package com.tamguo.modules.tiku.model.condition; package com.tamguo.modules.tiku.model.condition;
/**
* BookCondition
*/
public class BookCondition { public class BookCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 书籍 ID
private String id; private String id;
// 出版社
private String publishingHouse; private String publishingHouse;
// 书名
private String name; private String name;
// 课程 ID
private String courseId; private String courseId;
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
/**
* ID
* @return ID
*/
public String getCourseId() { public String getCourseId() {
return courseId; return courseId;
} }
/**
* ID
* @param courseId ID
*/
public void setCourseId(String courseId) { public void setCourseId(String courseId) {
this.courseId = courseId; this.courseId = courseId;
} }
/**
*
* @return
*/
public String getPublishingHouse() { public String getPublishingHouse() {
return publishingHouse; return publishingHouse;
} }
/**
*
* @param publishingHouse
*/
public void setPublishingHouse(String publishingHouse) { public void setPublishingHouse(String publishingHouse) {
this.publishingHouse = publishingHouse; this.publishingHouse = publishingHouse;
} }
/**
*
* @return
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
*
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
* ID
* @return ID
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* ID
* @param id ID
*/
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
}
}

@ -1,98 +1,42 @@
package com.tamguo.modules.tiku.model.condition; package com.tamguo.modules.tiku.model.condition;
/**
* ChapterCondition
*/
public class ChapterCondition { public class ChapterCondition {
// 父章节编码
private String parentCode; private String parentCode;
// 章节 ID
private String id; private String id;
// 章节名称
private String name; private String name;
// 所属书籍 ID
private String bookId; private String bookId;
// 所属书籍名称
private String bookName; private String bookName;
/**
*
* @return
*/
public String getParentCode() { public String getParentCode() {
return parentCode; return parentCode;
} }
/**
*
* @param parentCode
*/
public void setParentCode(String parentCode) { public void setParentCode(String parentCode) {
this.parentCode = parentCode; this.parentCode = parentCode;
} }
/**
* ID
* @return ID
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* ID
* @param id ID
*/
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
/**
*
* @return
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
*
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
* ID
* @return ID
*/
public String getBookId() { public String getBookId() {
return bookId; return bookId;
} }
/**
* ID
* @param bookId ID
*/
public void setBookId(String bookId) { public void setBookId(String bookId) {
this.bookId = bookId; this.bookId = bookId;
} }
/**
*
* @return
*/
public String getBookName() { public String getBookName() {
return bookName; return bookName;
} }
/**
*
* @param bookName
*/
public void setBookName(String bookName) { public void setBookName(String bookName) {
this.bookName = bookName; this.bookName = bookName;
} }
}
}

@ -1,117 +1,50 @@
package com.tamguo.modules.tiku.model.condition; package com.tamguo.modules.tiku.model.condition;
/**
* CourseCondition
*/
public class CourseCondition { public class CourseCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 课程 ID
private String id; private String id;
// 课程名称
private String name; private String name;
// 课程状态
private String status; private String status;
// 学科 ID
private String subjectId; private String subjectId;
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
/**
*
* @return
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
*
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
*
* @return
*/
public String getStatus() { public String getStatus() {
return status; return status;
} }
/**
*
* @param status
*/
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
/**
* ID
* @return ID
*/
public String getSubjectId() { public String getSubjectId() {
return subjectId; return subjectId;
} }
/**
* ID
* @param subjectId ID
*/
public void setSubjectId(String subjectId) { public void setSubjectId(String subjectId) {
this.subjectId = subjectId; this.subjectId = subjectId;
} }
/**
* ID
* @return ID
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* ID
* @param id ID
*/
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
}
}

@ -1,99 +1,43 @@
package com.tamguo.modules.tiku.model.condition; package com.tamguo.modules.tiku.model.condition;
/**
* SubjectCondition
*/
public class SubjectCondition { public class SubjectCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 用户 ID
private String uid; private String uid;
// 学科名称
private String name; private String name;
// 学科状态
private String status; private String status;
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
* ID
* @return ID
*/
public String getUid() { public String getUid() {
return uid; return uid;
} }
/**
* ID
* @param uid ID
*/
public void setUid(String uid) { public void setUid(String uid) {
this.uid = uid; this.uid = uid;
} }
/**
*
* @return
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
*
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
*
* @return
*/
public String getStatus() { public String getStatus() {
return status; return status;
} }
/**
*
* @param status
*/
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
}
}

@ -1,103 +1,54 @@
package com.tamguo.modules.tiku.model.enums; package com.tamguo.modules.tiku.model.enums;
import java.io.Serializable;
/** /**
* * (1.2.; 3.)
* (1. 2. 3. 4. 5. ) *
*
* @author tamguo * @author tamguo
*
*/ */
public enum QuestionTypeEnum { public enum QuestionTypeEnum {
/**
*
* @param value
* @param desc
*/
DANXUANTI("1", "单选题"), DANXUANTI("1", "单选题"),
/**
*
* @param value
* @param desc
*/
DUOXUANTI("2", "多选题"), DUOXUANTI("2", "多选题"),
/**
*
* @param value
* @param desc
*/
TIANKONGTI("3", "填空题"), TIANKONGTI("3", "填空题"),
/**
*
* @param value
* @param desc
*/
PANDUANTI("4", "判断题"), PANDUANTI("4", "判断题"),
/**
*
* @param value
* @param desc
*/
WENDATI("5", "问答题"); WENDATI("5", "问答题");
private String value; // 枚举值 private String value;
private String desc; // 描述 private String desc;
/** QuestionTypeEnum(final String value, final String desc) {
* this.value = value;
* @param value this.desc = desc;
* @param desc }
*/
QuestionTypeEnum(final String value, final String desc) { public static QuestionTypeEnum getQuestionType(String value) {
this.value = value; if("1".equals(value)) {
this.desc = desc; return DANXUANTI;
} }else if("2".equals(value)) {
return DUOXUANTI;
/** }else if("3".equals(value)) {
* value return TIANKONGTI;
* @param value value }else if("4".equals(value)) {
* @return WENDATI return PANDUANTI;
*/ }else if("5".equals(value)) {
public static QuestionTypeEnum getQuestionType(String value) { return WENDATI;
if ("1".equals(value)) { }
return DANXUANTI; return WENDATI;
} else if ("2".equals(value)) { }
return DUOXUANTI;
} else if ("3".equals(value)) { public Serializable getValue() {
return TIANKONGTI; return this.value;
} else if ("4".equals(value)) { }
return PANDUANTI;
} else if ("5".equals(value)) { public String getDesc(){
return WENDATI; return this.desc;
} }
return WENDATI;
} @Override
public String toString() {
/** return this.value;
* }
* @return
*/ }
public Serializable getValue() {
return this.value;
}
/**
*
* @return
*/
public String getDesc() {
return this.desc;
}
/**
*
* @return
*/
@Override
public String toString() {
return this.value;
}
}

@ -1,93 +1,79 @@
package com.tamguo.modules.tiku.service.impl; package com.tamguo.modules.tiku.service.impl;
import java.util.ArrayList; // 导入 ArrayList 类,用于存储章节列表 import java.util.ArrayList;
import java.util.List; // 导入 List 接口,用于存储章节实体列表 import java.util.List;
import org.apache.commons.lang3.StringUtils; // 导入StringUtils 类,用于字符串操作 import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; // 导入 Autowired 注解,用于依赖注入 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; // 导入 Service 注解,标识为服务层实现类 import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 导入 Transactional 注解,用于事务管理 import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray; // 导入 JSONArray 类,用于处理 JSON 数组 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; // 导入 JSONObject 类,用于处理 JSON 对象 import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition; // 导入 Condition 类,用于构建查询条件 import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.Page; // 导入 Page 类,用于分页查询 import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl; // 导入 ServiceImpl 类,作为服务层实现类的父类 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tamguo.common.utils.SystemConstant; // 导入 SystemConstant 类,用于定义系统常量 import com.tamguo.common.utils.SystemConstant;
import com.tamguo.modules.tiku.dao.KnowPointMapper; // 导入 KnowPointMapper 接口,用于知识关键点的数据访问 import com.tamguo.modules.tiku.dao.KnowPointMapper;
import com.tamguo.modules.tiku.dao.ChapterMapper; // 导入 ChapterMapper 接口,用于章节的数据访问 import com.tamguo.modules.tiku.dao.ChapterMapper;
import com.tamguo.modules.tiku.dao.CourseMapper; // 导入 CourseMapper 接口,用于课程的数据访问 import com.tamguo.modules.tiku.dao.CourseMapper;
import com.tamguo.modules.tiku.model.KnowPointEntity; // 导入 KnowPointEntity 类,代表知识关键点实体 import com.tamguo.modules.tiku.model.KnowPointEntity;
import com.tamguo.modules.tiku.model.ChapterEntity; // 导入 ChapterEntity 类,代表章节实体 import com.tamguo.modules.tiku.model.ChapterEntity;
import com.tamguo.modules.tiku.model.condition.ChapterCondition; // 导入 ChapterCondition 类,代表章节查询条件 import com.tamguo.modules.tiku.model.condition.ChapterCondition;
import com.tamguo.modules.tiku.model.enums.ChapterStatusEnum; // 导入 ChapterStatusEnum 枚举,代表章节状态 import com.tamguo.modules.tiku.model.enums.ChapterStatusEnum;
import com.tamguo.modules.tiku.service.IChapterService; // 导入 IChapterService 接口,定义章节服务的接口 import com.tamguo.modules.tiku.service.IChapterService;
@Service // 标识为服务层实现类 @Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity> implements IChapterService { public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity> implements IChapterService{
@Autowired // 自动注入 ChapterMapper 实例 @Autowired
private ChapterMapper chapterMapper; ChapterMapper chapterMapper;
@Autowired
@Autowired // 自动注入 CourseMapper 实例 CourseMapper courseMapper;
private CourseMapper courseMapper; @Autowired
KnowPointMapper bookMapper;
@Autowired // 自动注入 KnowPointMapper 实例
private KnowPointMapper bookMapper; @Transactional(readOnly=false)
@SuppressWarnings("unchecked")
/**
*
*
* @param bookId ID
* @return
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@SuppressWarnings("unchecked") // 抑制unchecked 警告
@Override @Override
public List<ChapterEntity> findChapterTree(String bookId) { public List<ChapterEntity> findChapterTree(String bookId) {
// 根据书籍 ID 查询章节列表
List<ChapterEntity> chapterList = baseMapper.selectList(Condition.create().eq("book_id", bookId)); List<ChapterEntity> chapterList = baseMapper.selectList(Condition.create().eq("book_id", bookId));
// 获取根章节 UID // 获取根chapter UID
String rootUid = StringUtils.EMPTY; String rootUid = StringUtils.EMPTY;
for (int i = 0; i < chapterList.size(); i++) { for(int i=0 ; i<chapterList.size() ; i++){
ChapterEntity chapter = chapterList.get(i); ChapterEntity chapter = chapterList.get(i);
if (chapter.getParentCode().equals(SystemConstant.CHAPTER_DEFAULT_ROOT_UID)) { if(chapter.getParentCode().equals(SystemConstant.CHAPTER_DEFAULT_ROOT_UID)){
rootUid = chapter.getId(); rootUid = chapter.getId();
} }
} }
// 获取第一层结构 // 获取第一层结构
List<ChapterEntity> entitys = new ArrayList<>(); List<ChapterEntity> entitys = new ArrayList<>();
for (int i = 0; i < chapterList.size(); i++) { for(int i=0 ; i<chapterList.size() ; i++){
ChapterEntity chapter = chapterList.get(i); ChapterEntity chapter = chapterList.get(i);
if (rootUid.equals(chapter.getParentCode())) { if(rootUid.equals(chapter.getParentCode())){
entitys.add(chapter); entitys.add(chapter);
} }
} }
for(int i=0 ; i<entitys.size() ; i++){
for (int i = 0; i < entitys.size(); i++) {
ChapterEntity entity = entitys.get(i); ChapterEntity entity = entitys.get(i);
// 获取子章节列表
List<ChapterEntity> childs = new ArrayList<>(); List<ChapterEntity> childs = new ArrayList<>();
for (int k = 0; k < chapterList.size(); k++) { for(int k=0 ; k<chapterList.size() ; k++){
ChapterEntity chapter = chapterList.get(k); ChapterEntity chapter = chapterList.get(k);
if (entity.getId().equals(chapter.getParentCode())) { if(entity.getId().equals(chapter.getParentCode())){
childs.add(chapter); childs.add(chapter);
} }
} }
entity.setChildChapterList(childs); entity.setChildChapterList(childs);
} }
for(int i=0 ; i<entitys.size() ; i++){
for (int i = 0; i < entitys.size(); i++) {
List<ChapterEntity> childs = entitys.get(i).getChildChapterList(); List<ChapterEntity> childs = entitys.get(i).getChildChapterList();
for (int k = 0; k < childs.size(); k++) { for(int k=0 ; k<childs.size() ; k++){
ChapterEntity child = childs.get(k); ChapterEntity child = childs.get(k);
// 获取子子章节列表
List<ChapterEntity> tmpChilds = new ArrayList<>(); List<ChapterEntity> tmpChilds = new ArrayList<>();
for (int n = 0; n < chapterList.size(); n++) { for(int n=0 ; n<chapterList.size() ; n++){
ChapterEntity chapter = chapterList.get(n); ChapterEntity chapter = chapterList.get(n);
if (child.getId().equals(chapter.getParentCode())) { if(child.getId().equals(chapter.getParentCode())){
tmpChilds.add(chapter); tmpChilds.add(chapter);
} }
} }
@ -97,98 +83,83 @@ public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity
return entitys; return entitys;
} }
/** @SuppressWarnings("unchecked")
*
*
* @param condition
* @return
*/
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Override @Override
public List<ChapterEntity> listData(ChapterCondition condition) { public List<ChapterEntity> listData(ChapterCondition condition) {
Condition query = Condition.create(); // 创建查询条件对象 Condition query = Condition.create();
if (!StringUtils.isEmpty(condition.getParentCode())) { if(!StringUtils.isEmpty(condition.getParentCode())) {
query.eq("parent_code", condition.getParentCode()); // 添加父章节代码条件 query.eq("parent_code", condition.getParentCode());
} else { }else {
query.eq("tree_level", "0"); // 添加树级别为 0 的条件(即根章节) query.eq("tree_level", "0");
} }
if (!StringUtils.isEmpty(condition.getId())) { if(!StringUtils.isEmpty(condition.getId())) {
query.eq("id", condition.getId()); // 添加章节 ID 条件 query.eq("id", condition.getId());
} }
if (!StringUtils.isEmpty(condition.getName())) { if(!StringUtils.isEmpty(condition.getName())) {
query.like("name", condition.getName()); // 添加章节名称模糊匹配条件 query.like("name", condition.getName());
} }
if (!StringUtils.isEmpty(condition.getBookId())) { if(!StringUtils.isEmpty(condition.getBookId())) {
query.andNew().eq("course_id", condition.getBookId()).or().eq("book_id", condition.getBookId()).or().eq("subject_id", condition.getBookId()); // 添加课程 ID、书籍 ID 或科目 ID 条件 query.andNew().eq("course_id", condition.getBookId()).or().eq("book_id", condition.getBookId()).or().eq("subject_id", condition.getBookId());;
} }
return chapterMapper.selectList(query); // 执行查询并返回结果 return chapterMapper.selectList(query);
} }
/** @SuppressWarnings("unchecked")
* ZTree JSON @Override
* public JSONArray treeData(String courseId, String excludeId) {
* @param chapterList List<ChapterEntity> chapterList = null;
* @return ZTree JSON if(StringUtils.isEmpty(excludeId)) {
*/ chapterList = chapterMapper.selectList(Condition.EMPTY);
} else {
chapterList = chapterMapper.selectList(Condition.create().notLike("parent_codes", excludeId).eq("id", excludeId));
}
return turnZTreeData(chapterList);
}
private JSONArray turnZTreeData(List<ChapterEntity> chapterList) { private JSONArray turnZTreeData(List<ChapterEntity> chapterList) {
if (chapterList!= null) { if(chapterList != null) {
JSONArray nodes = new JSONArray(); // 创建 JSON 数组对象 JSONArray nodes = new JSONArray();
for (int i = 0; i < chapterList.size(); i++) { for(int i=0 ; i<chapterList.size() ; i++) {
JSONObject node = new JSONObject(); // 创建 JSON 对象 JSONObject node = new JSONObject();
ChapterEntity office = chapterList.get(i); // 获取章节实体 ChapterEntity office = chapterList.get(i);
node.put("name", office.getName()); // 设置节点名称 node.put("name", office.getName());
node.put("id", office.getId()); // 设置节点 ID node.put("id", office.getId());
node.put("pId", office.getParentCode()); // 设置父节点 ID node.put("pId", office.getParentCode());
node.put("title", office.getName()); // 设置节点标题 node.put("title", office.getName());
nodes.add(node);
nodes.add(node); // 将节点添加到 JSON 数组中
} }
return nodes; // 返回 JSON 数组 return nodes;
} }
return null; // 如果章节列表为空,则返回 null return null;
} }
/** @Transactional(readOnly=false)
*
*
* @param chapter
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void save(ChapterEntity chapter) { public void save(ChapterEntity chapter) {
// 更新父章节的叶子节点状态为 false
ChapterEntity parentChapter = chapterMapper.selectById(chapter.getParentCode()); ChapterEntity parentChapter = chapterMapper.selectById(chapter.getParentCode());
parentChapter.setTreeLeaf(false); parentChapter.setTreeLeaf(false);
chapterMapper.updateById(parentChapter); chapterMapper.updateById(parentChapter);
chapter.setStatus(ChapterStatusEnum.NORMAL); // 设置章节状态为正常 chapter.setStatus(ChapterStatusEnum.NORMAL);
chapter.setTreeLeaf(true); // 设置章节为叶子节点 chapter.setTreeLeaf(true);
chapter.setTreeLevel(parentChapter.getTreeLevel() + 1); // 设置章节树级别 chapter.setTreeLevel(parentChapter.getTreeLevel() + 1);
chapter.setBookId(parentChapter.getBookId()); // 设置章节所属书籍 ID chapter.setBookId(parentChapter.getBookId());
chapterMapper.insert(chapter); // 插入章节记录 chapterMapper.insert(chapter);
// 更新章节的父章节代码列表
chapter.setParentCodes(parentChapter.getParentCodes() + chapter.getId() + ","); chapter.setParentCodes(parentChapter.getParentCodes() + chapter.getId() + ",");
chapterMapper.updateById(chapter); chapterMapper.updateById(chapter);
} }
/** @SuppressWarnings("unchecked")
* @Transactional(readOnly=false)
*
* @param chapter
*/
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void update(ChapterEntity chapter) { public void update(ChapterEntity chapter) {
// 更新父章节的叶子节点状态为 false ChapterEntity entity = chapterMapper.selectById(chapter.getId());
ChapterEntity parentChapter = chapterMapper.selectById(chapter.getParentCode()); ChapterEntity parentChapter = chapterMapper.selectById(chapter.getParentCode());
parentChapter.setTreeLeaf(false); parentChapter.setTreeLeaf(false);
chapterMapper.updateById(parentChapter); chapterMapper.updateById(parentChapter);
// 更新章节信息
ChapterEntity entity = chapterMapper.selectById(chapter.getId());
entity.setName(chapter.getName()); entity.setName(chapter.getName());
entity.setParentCode(chapter.getParentCode()); entity.setParentCode(chapter.getParentCode());
entity.setParentCodes(parentChapter.getParentCodes() + entity.getId() + ","); entity.setParentCodes(parentChapter.getParentCodes() + entity.getId() + ",");
@ -196,12 +167,12 @@ public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity
entity.setPointNum(chapter.getPointNum()); entity.setPointNum(chapter.getPointNum());
entity.setOrders(chapter.getOrders()); entity.setOrders(chapter.getOrders());
entity.setTreeLevel(entity.getParentCodes().split(",").length - 1); entity.setTreeLevel(entity.getParentCodes().split(",").length - 1);
// 更新子集章节的父章节代码列表和树级别 // 更新子集章节
List<ChapterEntity> chapterList = chapterMapper.selectList(Condition.create().like("parent_codes", entity.getId())); List<ChapterEntity> chapterList = chapterMapper.selectList(Condition.create().like("parent_codes", entity.getId()));
for (int i = 0; i < chapterList.size(); i++) { for(int i=0 ; i<chapterList.size() ; i++) {
ChapterEntity child = chapterList.get(i); ChapterEntity child = chapterList.get(i);
String subParentCodes = child.getParentCodes().substring(child.getParentCodes().indexOf(entity.getId()) + entity.getId().length() + 1); String subParentCodes = child.getParentCodes().substring(child.getParentCodes().indexOf(entity.getId()) + entity.getId().length() + 1);
child.setParentCodes(entity.getParentCodes() + subParentCodes); child.setParentCodes(entity.getParentCodes() + subParentCodes);
child.setTreeLevel(child.getParentCodes().split(",").length - 1); child.setTreeLevel(child.getParentCodes().split(",").length - 1);
@ -210,64 +181,40 @@ public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity
chapterMapper.updateById(entity); chapterMapper.updateById(entity);
} }
/** @Transactional(readOnly=false)
* @SuppressWarnings("unchecked")
*
* @param id ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Override @Override
public void delete(String id) { public void delete(String id) {
// 更新章节状态为已删除
ChapterEntity chapter = chapterMapper.selectById(id); ChapterEntity chapter = chapterMapper.selectById(id);
chapter.setStatus(ChapterStatusEnum.DELETE); chapter.setStatus(ChapterStatusEnum.DELETE);
chapterMapper.updateById(chapter); chapterMapper.updateById(chapter);
// 删除子章节 // 删除子章节
List<ChapterEntity> childs = chapterMapper.selectList(Condition.create().like("parent_codes", id)); List<ChapterEntity> childs = chapterMapper.selectList(Condition.create().like("parent_codes", id));
for (int i = 0; i < childs.size(); i++) { for(int i=0 ; i<childs.size() ; i++) {
ChapterEntity child = childs.get(i); ChapterEntity child = childs.get(i);
child.setStatus(ChapterStatusEnum.DELETE); child.setStatus(ChapterStatusEnum.DELETE);
chapterMapper.updateById(child); chapterMapper.updateById(child);
} }
} }
/** @Transactional(readOnly=true)
* ID @SuppressWarnings("unchecked")
*
* @param courseId ID
* @return
*/
@Transactional(readOnly = true) // 开启事务,设置只读为 true
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Override @Override
public List<ChapterEntity> findCourseChapter(String courseId) { public List<ChapterEntity> findCourseChapter(String courseId) {
// 根据课程 ID 查询知识关键点列表
List<KnowPointEntity> bookList = bookMapper.selectList(Condition.create().eq("course_id", courseId)); List<KnowPointEntity> bookList = bookMapper.selectList(Condition.create().eq("course_id", courseId));
if (bookList.size() == 0) { if(bookList.size() == 0) {
return null; // 如果没有找到知识关键点,则返回 null return null;
} }
Condition condition = Condition.create();
Condition condition = Condition.create(); // 创建查询条件对象 condition.eq("tree_level", 1);
condition.eq("tree_level", 1); // 设置树级别为 1 condition.eq("book_id", bookList.get(0).getId());
condition.eq("book_id", bookList.get(0).getId()); // 设置书籍 ID
// 根据条件查询章节列表
List<ChapterEntity> list = chapterMapper.selectPage(new Page<>(1, 5), condition); List<ChapterEntity> list = chapterMapper.selectPage(new Page<>(1, 5), condition);
return list; // 返回章节列表 return list;
} }
/** @Transactional(readOnly=true)
* ID
*
* @param parentCode
* @param id ID
* @return
*/
@Transactional(readOnly = true) // 开启事务,设置只读为 true
@Override @Override
public ChapterEntity selectNextChapter(String parentCode, String id) { public ChapterEntity selectNextChapter(String parentCode , String id) {
return chapterMapper.selectNextChapter(parentCode, id); // 查询下一个章节 return chapterMapper.selectNextChapter(parentCode , id);
} }
} }

@ -1,185 +1,125 @@
package com.tamguo.modules.tiku.service.impl; package com.tamguo.modules.tiku.service.impl;
import java.util.Arrays; // 导入 Arrays 类,用于操作数组 import java.util.Arrays;
import java.util.List; // 导入 List 接口,用于存储科目和课程实体列表 import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; // 导入 Autowired 注解,用于依赖注入 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; // 导入 Service 注解,标识为服务层实现类 import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 导入 Transactional 注解,用于事务管理 import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; // 导入 StringUtils 类,用于字符串操作 import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONArray; // 导入 JSONArray 类,用于处理 JSON 数组 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; // 导入 JSONObject 类,用于处理 JSON 对象 import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition; // 导入 Condition 类,用于构建查询条件 import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.Page; // 导入 Page 类,用于分页查询 import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl; // 导入 ServiceImpl 类,作为服务层实现类的父类 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tamguo.modules.tiku.dao.CourseMapper; // 导入 CourseMapper 接口,用于课程的数据访问 import com.tamguo.modules.tiku.dao.CourseMapper;
import com.tamguo.modules.tiku.dao.SubjectMapper; // 导入 SubjectMapper 接口,用于科目的数据访问 import com.tamguo.modules.tiku.dao.SubjectMapper;
import com.tamguo.modules.tiku.model.CourseEntity; // 导入 CourseEntity 类,代表课程实体 import com.tamguo.modules.tiku.model.CourseEntity;
import com.tamguo.modules.tiku.model.SubjectEntity; // 导入 SubjectEntity 类,代表科目实体 import com.tamguo.modules.tiku.model.SubjectEntity;
import com.tamguo.modules.tiku.model.condition.CourseCondition; // 导入 CourseCondition 类,代表课程查询条件 import com.tamguo.modules.tiku.model.condition.CourseCondition;
import com.tamguo.modules.tiku.model.enums.CourseStatusEnum; // 导入 CourseStatusEnum 枚举,代表课程状态 import com.tamguo.modules.tiku.model.enums.CourseStatusEnum;
import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum; // 导入 SubjectStatusEnum 枚举,代表科目状态 import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum;
import com.tamguo.modules.tiku.service.ICourseService; // 导入 ICourseService 接口,定义课程服务的接口 import com.tamguo.modules.tiku.service.ICourseService;
@Service // 标识为服务层实现类 @Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, CourseEntity> implements ICourseService { public class CourseServiceImpl extends ServiceImpl<CourseMapper, CourseEntity> implements ICourseService{
@Autowired // 自动注入 CourseMapper 实例 @Autowired
private CourseMapper courseMapper; public CourseMapper courseMapper;
@Autowired
@Autowired // 自动注入 SubjectMapper 实例 public SubjectMapper subjectMapper;
private SubjectMapper subjectMapper;
@SuppressWarnings("unchecked")
/** @Transactional(readOnly=true)
*
*
* @param condition
* @return
*/
@SuppressWarnings("unchecked") // 抑制unchecked 警告
@Transactional(readOnly = true) // 开启事务,设置只读为 true
@Override @Override
public Page<CourseEntity> listData(CourseCondition condition) { public Page<CourseEntity> listData(CourseCondition condition) {
Page<CourseEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize()); // 创建分页对象 Page<CourseEntity> page = new Page<>(condition.getPageNo() , condition.getPageSize());
Condition query = Condition.create();
Condition query = Condition.create(); // 创建查询条件对象 if(!StringUtils.isEmpty(condition.getId())) {
if (!StringUtils.isEmpty(condition.getId())) { query.eq("id", condition.getId());
query.eq("id", condition.getId()); // 添加课程 ID 条件
} }
if (!StringUtils.isEmpty(condition.getName())) { if(!StringUtils.isEmpty(condition.getName())) {
query.like("name", condition.getName()); // 添加课程名称模糊匹配条件 query.like("name", condition.getName());
} }
if (!StringUtils.isEmpty(condition.getSubjectId())) { if(!StringUtils.isEmpty(condition.getSubjectId())) {
query.eq("subject_id", condition.getSubjectId()); // 添加科目 ID 条件 query.eq("subject_id", condition.getSubjectId());
} }
if (!StringUtils.isEmpty(condition.getStatus())) { if(!StringUtils.isEmpty(condition.getStatus())) {
query.eq("status", condition.getStatus()); // 添加课程状态条件 query.eq("status", condition.getStatus());
} }
query.orderAsc(Arrays.asList("sort")); // 根据排序字段升序排序 query.orderAsc(Arrays.asList("sort"));
return page.setRecords(courseMapper.selectPage(page , query));
return page.setRecords(courseMapper.selectPage(page, query)); // 执行查询并设置分页结果
} }
/** @Transactional(readOnly=false)
*
*
* @param course
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void save(CourseEntity course) { public void save(CourseEntity course) {
course.setStatus(CourseStatusEnum.NORMAL); // 设置课程状态为正常 course.setStatus(CourseStatusEnum.NORMAL);
courseMapper.insert(course); // 插入课程记录 courseMapper.insert(course);
} }
/** @Transactional(readOnly=false)
*
*
* @param course
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void update(CourseEntity course) { public void update(CourseEntity course) {
CourseEntity entity = courseMapper.selectById(course.getId()); // 获取要更新的课程实体 CourseEntity entity = courseMapper.selectById(course.getId());
entity.setName(course.getName());
entity.setName(course.getName()); // 更新课程名称 entity.setSubjectId(course.getSubjectId());
entity.setSubjectId(course.getSubjectId()); // 更新科目 ID entity.setSort(course.getSort());
entity.setSort(course.getSort()); // 更新排序号 entity.setRemarks(course.getRemarks());
entity.setRemarks(course.getRemarks()); // 更新备注 courseMapper.updateById(entity);
courseMapper.updateById(entity); // 更新课程记录
} }
/** @Transactional(readOnly=false)
*
*
* @param uid ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void delete(String uid) { public void delete(String uid) {
CourseEntity entity = courseMapper.selectById(uid); // 获取要删除的课程实体 CourseEntity entity = courseMapper.selectById(uid);
entity.setStatus(CourseStatusEnum.DELETE);
entity.setStatus(CourseStatusEnum.DELETE); // 设置课程状态为已删除 courseMapper.updateById(entity);
courseMapper.updateById(entity); // 更新课程记录
} }
/** @Transactional(readOnly=false)
*
*
* @param uid ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void enable(String uid) { public void enable(String uid) {
CourseEntity entity = courseMapper.selectById(uid); // 获取要启用的课程实体 CourseEntity entity = courseMapper.selectById(uid);
entity.setStatus(CourseStatusEnum.NORMAL);
entity.setStatus(CourseStatusEnum.NORMAL); // 设置课程状态为正常 courseMapper.updateById(entity);
courseMapper.updateById(entity); // 更新课程记录
} }
/** @Transactional(readOnly=false)
*
*
* @param uid ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void disabled(String uid) { public void disabled(String uid) {
CourseEntity entity = courseMapper.selectById(uid); // 获取要禁用的课程实体 CourseEntity entity = courseMapper.selectById(uid);
entity.setStatus(CourseStatusEnum.DISABLED);
entity.setStatus(CourseStatusEnum.DISABLED); // 设置课程状态为禁用 courseMapper.updateById(entity);
courseMapper.updateById(entity); // 更新课程记录
} }
/** @SuppressWarnings("unchecked")
* ZTree JSON
*
* @return ZTree JSON
*/
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public JSONArray treeData() { public JSONArray treeData() {
List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.create().eq("status", SubjectStatusEnum.NORMAL.getValue())); // 查询正常状态的科目列表 List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.create().eq("status", SubjectStatusEnum.NORMAL.getValue()));
List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("status", CourseStatusEnum.NORMAL.getValue())); // 查询正常状态的课程列表 List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("status", CourseStatusEnum.NORMAL.getValue()));
return transform(subjectList, courseList);
return transform(subjectList, courseList); // 转换科目和课程数据为 JSON 数组
} }
/** private JSONArray transform(List<SubjectEntity> subjectList , List<CourseEntity> courseList) {
* ZTree JSON JSONArray entitys = new JSONArray();
* for(int i=0 ; i<subjectList.size() ; i++) {
* @param subjectList JSONObject entity = new JSONObject();
* @param courseList entity.put("id", subjectList.get(i).getId());
* @return ZTree JSON entity.put("name", subjectList.get(i).getName());
*/ entity.put("pId", "0");
private JSONArray transform(List<SubjectEntity> subjectList, List<CourseEntity> courseList) { entitys.add(entity);
JSONArray entitys = new JSONArray(); // 创建 JSON 数组对象
for (int i = 0; i < subjectList.size(); i++) {
JSONObject entity = new JSONObject(); // 创建 JSON 对象
SubjectEntity subject = subjectList.get(i); // 获取科目实体
entity.put("id", subject.getId()); // 设置科目 ID
entity.put("name", subject.getName()); // 设置科目名称
entity.put("pId", "0"); // 设置父节点 ID 为 0
entitys.add(entity); // 将科目对象添加到 JSON 数组中
} }
for(int i=0 ; i<courseList.size() ; i++) {
for (int i = 0; i < courseList.size(); i++) { JSONObject entity = new JSONObject();
JSONObject entity = new JSONObject(); // 创建 JSON 对象 entity.put("id", courseList.get(i).getId());
entity.put("name", courseList.get(i).getName());
CourseEntity course = courseList.get(i); // 获取课程实体 entity.put("pId", courseList.get(i).getSubjectId());
entity.put("id", course.getId()); // 设置课程 ID entitys.add(entity);
entity.put("name", course.getName()); // 设置课程名称
entity.put("pId", course.getSubjectId()); // 设置父节点 ID 为课程所属科目 ID
entitys.add(entity); // 将课程对象添加到 JSON 数组中
} }
return entitys;
return entitys; // 返回转换后的 JSON 数组
} }
}
}

@ -1,192 +1,129 @@
package com.tamguo.modules.tiku.service.impl; package com.tamguo.modules.tiku.service.impl;
import java.util.List; // 导入 List 接口,用于存储科目、课程和知识点实体列表 import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; // 导入 Autowired 注解,用于依赖注入 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; // 导入 Service 注解,标识为服务层实现类 import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 导入 Transactional 注解,用于事务管理 import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray; // 导入 JSONArray 类,用于处理 JSON 数组 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; // 导入 JSONObject 类,用于处理 JSON 对象 import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition; // 导入 Condition 类,用于构建查询条件 import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.Page; // 导入 Page 类,用于分页查询 import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl; // 导入 ServiceImpl 类,作为服务层实现类的父类 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tamguo.modules.tiku.dao.KnowPointMapper; // 导入 KnowPointMapper 接口,用于知识点的数据访问 import com.tamguo.modules.tiku.dao.KnowPointMapper;
import com.tamguo.modules.tiku.dao.CourseMapper; // 导入 CourseMapper 接口,用于课程的数据访问 import com.tamguo.modules.tiku.dao.CourseMapper;
import com.tamguo.modules.tiku.dao.SubjectMapper; // 导入 SubjectMapper 接口,用于科目的数据访问 import com.tamguo.modules.tiku.dao.SubjectMapper;
import com.tamguo.modules.tiku.model.KnowPointEntity; // 导入 KnowPointEntity 类,代表知识点实体 import com.tamguo.modules.tiku.model.KnowPointEntity;
import com.tamguo.modules.tiku.model.CourseEntity; // 导入 CourseEntity 类,代表课程实体 import com.tamguo.modules.tiku.model.CourseEntity;
import com.tamguo.modules.tiku.model.SubjectEntity; // 导入 SubjectEntity 类,代表科目实体 import com.tamguo.modules.tiku.model.SubjectEntity;
import com.tamguo.modules.tiku.model.condition.BookCondition; // 导入 BookCondition 类,代表知识点查询条件 import com.tamguo.modules.tiku.model.condition.BookCondition;
import com.tamguo.modules.tiku.model.enums.BookStatusEnum; // 导入 BookStatusEnum 枚举,代表知识点状态 import com.tamguo.modules.tiku.model.enums.BookStatusEnum;
import com.tamguo.modules.tiku.model.enums.CourseStatusEnum; // 导入 CourseStatusEnum 枚举,代表课程状态 import com.tamguo.modules.tiku.model.enums.CourseStatusEnum;
import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum; // 导入 SubjectStatusEnum 枚举,代表科目状态 import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum;
import com.tamguo.modules.tiku.service.IKnowPointService; // 导入 IKnowPointService 接口,定义知识点服务的接口 import com.tamguo.modules.tiku.service.IKnowPointService;
@Service // 标识为服务层实现类 @Service
public class KnowPointServiceImpl extends ServiceImpl<KnowPointMapper, KnowPointEntity> implements IKnowPointService { public class KnowPointServiceImpl extends ServiceImpl<KnowPointMapper, KnowPointEntity> implements IKnowPointService{
@Autowired // 自动注入 KnowPointMapper 实例 @Autowired
private KnowPointMapper knowPointMapper; KnowPointMapper knowPointMapper;
@Autowired
@Autowired // 自动注入 CourseMapper 实例 CourseMapper courseMapper;
private CourseMapper courseMapper; @Autowired
SubjectMapper subjectMapper;
@Autowired // 自动注入 SubjectMapper 实例
private SubjectMapper subjectMapper; @Transactional(readOnly=false)
/**
*
*
* @param condition
* @return
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public Page<KnowPointEntity> listData(BookCondition condition) { public Page<KnowPointEntity> listData(BookCondition condition) {
Page<KnowPointEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize()); // 创建分页对象 Page<KnowPointEntity> page = new Page<>(condition.getPageNo() , condition.getPageSize());
return page.setRecords(knowPointMapper.listData(page, condition)); // 执行查询并设置分页结果 return page.setRecords(knowPointMapper.listData(page, condition));
} }
/** @Transactional(readOnly=false)
*
*
* @param book
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void save(KnowPointEntity book) { public void save(KnowPointEntity book) {
CourseEntity course = courseMapper.selectById(book.getCourseId()); // 获取课程实体 CourseEntity course = courseMapper.selectById(book.getCourseId());
book.setStatus(BookStatusEnum.NORMAL); // 设置知识点状态为正常 book.setStatus(BookStatusEnum.NORMAL);
book.setSubjectId(course.getSubjectId()); // 设置知识点所属科目 ID book.setSubjectId(course.getSubjectId());
knowPointMapper.insert(book); // 插入知识点记录 knowPointMapper.insert(book);
} }
/** @Transactional(readOnly=false)
*
*
* @param book
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void update(KnowPointEntity book) { public void update(KnowPointEntity book) {
CourseEntity course = courseMapper.selectById(book.getCourseId()); // 获取课程实体 CourseEntity course = courseMapper.selectById(book.getCourseId());
KnowPointEntity entity = knowPointMapper.selectById(book.getId()); // 获取要更新的知识点实体 KnowPointEntity entity = knowPointMapper.selectById(book.getId());
entity.setName(book.getName()); // 更新知识点名称 entity.setName(book.getName());
entity.setPointNum(book.getPointNum()); // 更新知识点数量 entity.setPointNum(book.getPointNum());
entity.setQuestionNum(book.getQuestionNum()); // 更新问题数量 entity.setQuestionNum(book.getQuestionNum());
entity.setRemarks(book.getRemarks()); // 更新备注 entity.setRemarks(book.getRemarks());
entity.setPublishingHouse(book.getPublishingHouse()); // 更新出版社 entity.setPublishingHouse(book.getPublishingHouse());
entity.setSort(book.getSort()); // 更新排序号 entity.setSort(book.getSort());
entity.setCourseId(course.getId()); // 更新课程 ID entity.setCourseId(course.getId());
knowPointMapper.updateById(entity); // 更新知识点记录 knowPointMapper.updateById(entity);
} }
/** @Transactional(readOnly=false)
*
*
* @param id ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void delete(String id) { public void delete(String id) {
KnowPointEntity book = knowPointMapper.selectById(id); // 获取要删除的知识点实体 KnowPointEntity book = knowPointMapper.selectById(id);
book.setStatus(BookStatusEnum.DELETE);
book.setStatus(BookStatusEnum.DELETE); // 设置知识点状态为已删除 knowPointMapper.updateById(book);
knowPointMapper.updateById(book); // 更新知识点记录
} }
/** @Transactional(readOnly=false)
*
*
* @param id ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void enable(String id) { public void enable(String id) {
KnowPointEntity book = knowPointMapper.selectById(id); // 获取要启用的知识点实体 KnowPointEntity book = knowPointMapper.selectById(id);
book.setStatus(BookStatusEnum.NORMAL);
book.setStatus(BookStatusEnum.NORMAL); // 设置知识点状态为正常 knowPointMapper.updateById(book);
knowPointMapper.updateById(book); // 更新知识点记录
} }
/** @Transactional(readOnly=false)
*
*
* @param id ID
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@Override @Override
public void disabled(String id) { public void disabled(String id) {
KnowPointEntity book = knowPointMapper.selectById(id); // 获取要禁用的知识点实体 KnowPointEntity book = knowPointMapper.selectById(id);
book.setStatus(BookStatusEnum.DISABLED);
book.setStatus(BookStatusEnum.DISABLED); // 设置知识点状态为禁用 knowPointMapper.updateById(book);
knowPointMapper.updateById(book); // 更新知识点记录
} }
/** @Transactional(readOnly=false)
* ZTree JSON @SuppressWarnings("unchecked")
*
* @return ZTree JSON
*/
@Transactional(readOnly = false) // 开启事务,设置只读为 false
@SuppressWarnings("unchecked") // 抑制 unchecked 警告
@Override @Override
public JSONArray treeData() { public JSONArray treeData() {
List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.create().eq("status", SubjectStatusEnum.NORMAL.getValue())); // 查询正常状态的科目列表 List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.create().eq("status", SubjectStatusEnum.NORMAL.getValue()));
List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("status", CourseStatusEnum.NORMAL.getValue())); // 查询正常状态的课程列表 List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("status", CourseStatusEnum.NORMAL.getValue()));
List<KnowPointEntity> bookList = knowPointMapper.selectList(Condition.create().eq("status", BookStatusEnum.NORMAL.getValue())); // 查询正常状态的知识点列表 List<KnowPointEntity> bookList = knowPointMapper.selectList(Condition.create().eq("status", BookStatusEnum.NORMAL.getValue()));
return transform(subjectList, courseList , bookList);
return transform(subjectList, courseList, bookList); // 转换科目、课程和知识点数据为 JSON 数组
} }
/** private JSONArray transform(List<SubjectEntity> subjectList , List<CourseEntity> courseList , List<KnowPointEntity> bookList) {
* ZTree JSON JSONArray entitys = new JSONArray();
* for(int i=0 ; i<subjectList.size() ; i++) {
* @param subjectList JSONObject entity = new JSONObject();
* @param courseList entity.put("id", subjectList.get(i).getId());
* @param bookList entity.put("name", subjectList.get(i).getName());
* @return ZTree JSON entity.put("pId", "0");
*/ entitys.add(entity);
private JSONArray transform(List<SubjectEntity> subjectList, List<CourseEntity> courseList, List<KnowPointEntity> bookList) {
JSONArray entitys = new JSONArray(); // 创建 JSON 数组对象
for (int i = 0; i < subjectList.size(); i++) {
JSONObject entity = new JSONObject(); // 创建 JSON 对象
SubjectEntity subject = subjectList.get(i); // 获取科目实体
entity.put("id", subject.getId()); // 设置科目 ID
entity.put("name", subject.getName()); // 设置科目名称
entity.put("pId", "0"); // 设置父节点 ID 为 0
entitys.add(entity); // 将科目对象添加到 JSON 数组中
} }
for(int i=0 ; i<courseList.size() ; i++) {
for (int i = 0; i < courseList.size(); i++) { JSONObject entity = new JSONObject();
JSONObject entity = new JSONObject(); // 创建 JSON 对象 entity.put("id", courseList.get(i).getId());
entity.put("name", courseList.get(i).getName());
CourseEntity course = courseList.get(i); // 获取课程实体 entity.put("pId", courseList.get(i).getSubjectId());
entity.put("id", course.getId()); // 设置课程 ID entitys.add(entity);
entity.put("name", course.getName()); // 设置课程名称
entity.put("pId", course.getSubjectId()); // 设置父节点 ID 为课程所属科目 ID
entitys.add(entity); // 将课程对象添加到 JSON 数组中
} }
for(int i=0 ; i<bookList.size() ; i++) {
for (int i = 0; i < bookList.size(); i++) { JSONObject entity = new JSONObject();
JSONObject entity = new JSONObject(); // 创建 JSON 对象 entity.put("id", bookList.get(i).getId());
entity.put("name", bookList.get(i).getName());
KnowPointEntity book = bookList.get(i); // 获取知识点实体 entity.put("pId", bookList.get(i).getCourseId());
entity.put("id", book.getId()); // 设置知识点 ID entitys.add(entity);
entity.put("name", book.getName()); // 设置知识点名称
entity.put("pId", book.getCourseId()); // 设置父节点 ID 为知识点所属课程 ID
entitys.add(entity); // 将知识点对象添加到 JSON 数组中
} }
return entitys;
return entitys; // 返回转换后的 JSON 数组
} }
} }

@ -2,7 +2,6 @@ package com.tamguo.modules.tiku.service.impl;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -14,136 +13,100 @@ import com.tamguo.modules.tiku.dao.MenuMapper;
import com.tamguo.modules.tiku.model.MenuEntity; import com.tamguo.modules.tiku.model.MenuEntity;
import com.tamguo.modules.tiku.service.IMenuService; import com.tamguo.modules.tiku.service.IMenuService;
/**
* MenuServiceImpl IMenuService
*/
@Service @Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements IMenuService { public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements IMenuService{
/**
* MenuMapper
*/
@Autowired @Autowired
private MenuMapper menuMapper; private MenuMapper menuMapper;
/**
*
*/
@Autowired @Autowired
private CacheService cacheService; private CacheService cacheService;
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> findMenus() { public List<MenuEntity> findMenus() {
List<MenuEntity> menuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.INDEX_MENU)); List<MenuEntity> menuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.INDEX_MENU));
if (menuList == null) { if (menuList == null) {
menuList = menuMapper.selectList(Condition.create().eq("parent_id", 1).eq("is_show", 1).orderDesc(Arrays.asList("orders"))); menuList = menuMapper.selectList(Condition.create().eq("parent_id", 1).eq("is_show", 1).orderDesc(Arrays.asList("orders")));
for (MenuEntity menu : menuList) { for(MenuEntity menu : menuList){
List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders"))); List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders")));
menu.setChildSubjects(childSubjects); menu.setChildSubjects(childSubjects);
} }
cacheService.setObject(SystemConstant.INDEX_MENU, menuList, 2 * 60 * 60); cacheService.setObject(SystemConstant.INDEX_MENU, menuList , 2 * 60 * 60);
} }
return menuList; return menuList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> findAllMenus() { public List<MenuEntity> findAllMenus() {
List<MenuEntity> allMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.ALL_INDEX_MENU)); List<MenuEntity> allMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.ALL_INDEX_MENU));
if (allMenuList == null) { if(allMenuList == null){
allMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 1).orderDesc(Arrays.asList("orders"))); allMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 1).orderDesc(Arrays.asList("orders")));
for (MenuEntity menu : allMenuList) { for(MenuEntity menu : allMenuList){
List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders"))); List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders")));
menu.setChildSubjects(childSubjects); menu.setChildSubjects(childSubjects);
} }
cacheService.setObject(SystemConstant.ALL_INDEX_MENU, allMenuList, 2 * 60 * 60); cacheService.setObject(SystemConstant.ALL_INDEX_MENU, allMenuList , 2 * 60 * 60);
} }
return allMenuList; return allMenuList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> findLeftMenus() { public List<MenuEntity> findLeftMenus() {
List<MenuEntity> leftMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.LEFT_INDEX_MENU)); List<MenuEntity> leftMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.LEFT_INDEX_MENU));
if (leftMenuList == null) { if(leftMenuList == null){
leftMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 2).orderDesc(Arrays.asList("orders"))); leftMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 2).orderDesc(Arrays.asList("orders")));
for (MenuEntity menu : leftMenuList) { for(MenuEntity menu : leftMenuList){
List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders"))); List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders")));
menu.setChildSubjects(childSubjects); menu.setChildSubjects(childSubjects);
} }
cacheService.setObject(SystemConstant.LEFT_INDEX_MENU, leftMenuList, 2 * 60 * 60); cacheService.setObject(SystemConstant.LEFT_INDEX_MENU, leftMenuList , 2 * 60 * 60);
} }
return leftMenuList; return leftMenuList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> findChapterMenus() { public List<MenuEntity> findChapterMenus() {
List<MenuEntity> chapterMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.CHAPTER_INDEX_MENU)); List<MenuEntity> chapterMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.CHAPTER_INDEX_MENU));
if (chapterMenuList == null) { if(chapterMenuList == null){
chapterMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 4).orderAsc(Arrays.asList("orders"))); chapterMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 4).orderAsc(Arrays.asList("orders")));
for (MenuEntity menu : chapterMenuList) { for(MenuEntity menu : chapterMenuList){
List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders"))); List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders")));
menu.setChildSubjects(childSubjects); menu.setChildSubjects(childSubjects);
} }
cacheService.setObject(SystemConstant.CHAPTER_INDEX_MENU, chapterMenuList, 2 * 60 * 60); cacheService.setObject(SystemConstant.CHAPTER_INDEX_MENU, chapterMenuList , 2 * 60 * 60);
} }
return chapterMenuList; return chapterMenuList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> findFooterMenus() { public List<MenuEntity> findFooterMenus() {
List<MenuEntity> footerMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.FOOTER_INDEX_MENU)); List<MenuEntity> footerMenuList = ((List<MenuEntity>) cacheService.getObject(SystemConstant.FOOTER_INDEX_MENU));
if (footerMenuList == null) { if(footerMenuList == null){
footerMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 3).orderDesc(Arrays.asList("orders"))); footerMenuList = menuMapper.selectList(Condition.create().eq("parent_id", 3).orderDesc(Arrays.asList("orders")));
for (MenuEntity menu : footerMenuList) { for(MenuEntity menu : footerMenuList){
List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders"))); List<MenuEntity> childSubjects = menuMapper.selectList(Condition.create().eq("parent_id", menu.getId()).orderDesc(Arrays.asList("orders")));
menu.setChildSubjects(childSubjects); menu.setChildSubjects(childSubjects);
} }
cacheService.setObject(SystemConstant.FOOTER_INDEX_MENU, footerMenuList, 2 * 60 * 60); cacheService.setObject(SystemConstant.FOOTER_INDEX_MENU, footerMenuList , 2 * 60 * 60);
} }
return footerMenuList; return footerMenuList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<MenuEntity> getMenuTree() { public List<MenuEntity> getMenuTree() {
return menuMapper.selectList(Condition.EMPTY); return menuMapper.selectList(Condition.EMPTY);
} }
/**
* ID
* @param uid ID
* @return
*/
@Override @Override
public MenuEntity findById(String uid) { public MenuEntity findById(String uid) {
return menuMapper.selectById(uid); return menuMapper.selectById(uid);
} }
}
}

@ -27,134 +27,84 @@ import com.tamguo.modules.tiku.service.ICourseService;
import com.tamguo.modules.tiku.service.IPaperService; import com.tamguo.modules.tiku.service.IPaperService;
import com.tamguo.modules.tiku.service.ISubjectService; import com.tamguo.modules.tiku.service.ISubjectService;
/**
* PaperServiceImpl IPaperService
*/
@Service @Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, PaperEntity> implements IPaperService { public class PaperServiceImpl extends ServiceImpl<PaperMapper, PaperEntity> implements IPaperService{
/**
* ISubjectService
*/
@Autowired @Autowired
private ISubjectService iSubjectService; private ISubjectService iSubjectService;
/**
* ICourseService
*/
@Autowired @Autowired
private ICourseService iCourseService; private ICourseService iCourseService;
/**
* ISysAreaService
*/
@Autowired @Autowired
private ISysAreaService iSysAreaService; private ISysAreaService iSysAreaService;
/**
* PaperMapper
*/
@Autowired @Autowired
private PaperMapper paperMapper; private PaperMapper paperMapper;
/**
* CacheService
*/
@Autowired @Autowired
private CacheService cacheService; private CacheService cacheService;
/**
* QuestionMapper
*/
@Autowired @Autowired
private QuestionMapper questionMapper; private QuestionMapper questionMapper;
/**
* QuestionOptionsMapper
*/
@Autowired @Autowired
private QuestionOptionsMapper questionOptionsMapper; private QuestionOptionsMapper questionOptionsMapper;
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<PaperEntity> findHistoryPaper() { public List<PaperEntity> findHistoryPaper() {
List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.HISTORY_PAPER); List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.HISTORY_PAPER);
if (paperList == null) { if(paperList == null){
Page<PaperEntity> page = new Page<>(1, 6); Page<PaperEntity> page = new Page<>(1 , 6);
paperList = paperMapper.selectPage(page, Condition.create().eq("type", SystemConstant.ZHENGTI_PAPER_ID).orderDesc(Arrays.asList("id"))); paperList = paperMapper.selectPage(page, Condition.create().eq("type", SystemConstant.ZHENGTI_PAPER_ID).orderDesc(Arrays.asList("id")));
for (int i = 0; i < paperList.size(); i++) { for(int i=0 ; i<paperList.size() ; i++) {
PaperEntity paper = paperList.get(i); PaperEntity paper = paperList.get(i);
paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName()); paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName());
paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName()); paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName());
paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName()); paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName());
} }
cacheService.setObject(SystemConstant.HISTORY_PAPER, paperList, 2 * 60 * 60); cacheService.setObject(SystemConstant.HISTORY_PAPER, paperList , 2 * 60 * 60);
} }
return paperList; return paperList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<PaperEntity> findSimulationPaper() { public List<PaperEntity> findSimulationPaper() {
List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.SIMULATION_PAPER); List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.SIMULATION_PAPER);
if (paperList == null) { if(paperList == null){
Page<PaperEntity> page = new Page<>(1, 6); Page<PaperEntity> page = new Page<>(1 , 6);
paperList = paperMapper.selectPage(page, Condition.create().eq("type", SystemConstant.MONI_PAPER_ID).orderDesc(Arrays.asList("id"))); paperList = paperMapper.selectPage(page, Condition.create().eq("type", SystemConstant.MONI_PAPER_ID).orderDesc(Arrays.asList("id")));
for (int i = 0; i < paperList.size(); i++) { for(int i=0 ; i<paperList.size() ; i++) {
PaperEntity paper = paperList.get(i); PaperEntity paper = paperList.get(i);
paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName()); paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName());
paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName()); paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName());
paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName()); paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName());
} }
cacheService.setObject(SystemConstant.SIMULATION_PAPER, paperList, 2 * 60 * 60); cacheService.setObject(SystemConstant.SIMULATION_PAPER, paperList , 2 * 60 * 60);
} }
return paperList; return paperList;
} }
/**
*
* @param areaId ID
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<PaperEntity> findHotPaper(String areaId) { public List<PaperEntity> findHotPaper(String areaId) {
List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.HOT_PAPER); List<PaperEntity> paperList = (List<PaperEntity>) cacheService.getObject(SystemConstant.HOT_PAPER);
if (paperList == null) { if(paperList == null){
Page<PaperEntity> page = new Page<>(1, 10); Page<PaperEntity> page = new Page<>(1 , 10);
paperList = paperMapper.selectPage(page, Condition.create().orderDesc(Arrays.asList("id"))); paperList = paperMapper.selectPage(page, Condition.create().orderDesc(Arrays.asList("id")));
for (int i = 0; i < paperList.size(); i++) { for(int i=0 ; i<paperList.size() ; i++) {
PaperEntity paper = paperList.get(i); PaperEntity paper = paperList.get(i);
paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName()); paper.setSubjectName(iSubjectService.selectById(paper.getSubjectId()).getName());
paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName()); paper.setCourseName(iCourseService.selectById(paper.getCourseId()).getName());
paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName()); paper.setAreaName(iSysAreaService.selectById(paper.getAreaId()).getAreaName());
} }
cacheService.setObject(SystemConstant.HOT_PAPER, paperList, 2 * 60 * 60); cacheService.setObject(SystemConstant.HOT_PAPER, paperList , 2 * 60 * 60);
} }
return paperList; return paperList;
} }
/** @Transactional(readOnly=false)
*
* @param paperId ID
* @param title
* @param name
* @param type
*/
@Transactional(readOnly = false)
@Override @Override
public void addPaperQuestionInfo(String paperId, String title, String name, String type) { public void addPaperQuestionInfo(String paperId, String title, String name, String type) {
PaperEntity paper = paperMapper.selectById(paperId); PaperEntity paper = paperMapper.selectById(paperId);
String questionInfo = paper.getQuestionInfo(); String questionInfo = paper.getQuestionInfo();
JSONArray qList = JSONArray.parseArray(questionInfo); JSONArray qList = JSONArray.parseArray(questionInfo);
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put("name", name); entity.put("name", name);
@ -162,74 +112,53 @@ public class PaperServiceImpl extends ServiceImpl<PaperMapper, PaperEntity> impl
entity.put("type", type); entity.put("type", type);
entity.put("id", UUID.randomUUID().toString()); entity.put("id", UUID.randomUUID().toString());
qList.add(entity); qList.add(entity);
paper.setQuestionInfo(qList.toString()); paper.setQuestionInfo(qList.toString());
paperMapper.updateById(paper); paperMapper.updateById(paper);
} }
/** @Transactional(readOnly=false)
*
* @param paperId ID
* @param title
* @param name
* @param type
* @param uid ID
*/
@Transactional(readOnly = false)
@Override @Override
public void updatePaperQuestionInfo(String paperId, String title, String name, String type, String uid) { public void updatePaperQuestionInfo(String paperId, String title, String name, String type, String uid) {
PaperEntity paper = paperMapper.selectById(paperId); PaperEntity paper = paperMapper.selectById(paperId);
JSONArray qList = JSONArray.parseArray(paper.getQuestionInfo()); JSONArray qList = JSONArray.parseArray(paper.getQuestionInfo());
for (int i = 0; i < qList.size(); i++) { for(int i =0 ; i<qList.size() ; i++){
JSONObject q = qList.getJSONObject(i); JSONObject q = qList.getJSONObject(i);
if (q.getString("id").equals(uid)) { if(q.getString("id").equals(uid)){
q.put("name", name); q.put("name", name);
q.put("title", title); q.put("title", title);
q.put("type", type); q.put("type", type);
} }
} }
paper.setQuestionInfo(qList.toString()); paper.setQuestionInfo(qList.toString());
paperMapper.updateById(paper); paperMapper.updateById(paper);
} }
/**
*
* @param currMemberId ID
* @param paperId ID
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Result deletePaper(String CurrMemberId, String paperId) { public Result deletePaper(String currMemberId , String paperId) {
PaperEntity paper = paperMapper.selectById(paperId); PaperEntity paper = paperMapper.selectById(paperId);
if (!currMemberId.equals(paper.getCreaterId())) { if(!currMemberId.equals(paper.getCreaterId())) {
return Result.result(501, null, "不能删除其他人的试卷!"); return Result.result(501, null , "不能删除其他人的试卷!");
} }
paperMapper.deleteById(paperId); paperMapper.deleteById(paperId);
// 删除试题 // 删除试题
questionMapper.delete(Condition.create().eq("paper_id", paperId)); questionMapper.delete(Condition.create().eq("paper_id", paperId));
return Result.result(Result.SUCCESS_CODE, null, "删除成功!"); return Result.result(Result.SUCCESS_CODE, null , "删除成功!");
} }
/** @Transactional(readOnly=false)
*
* @param CurrMemberId ID
* @param paperId ID
* @param cuid ID
* @return
*/
@Transactional(readOnly = false)
@Override @Override
public Result deletePaperQuestionInfoBtn(String CurrMemberId, String paperId, String cuid) { public Result deletePaperQuestionInfoBtn(String currMemberId , String paperId, String cuid) {
PaperEntity paper = paperMapper.selectById(paperId); PaperEntity paper = paperMapper.selectById(paperId);
if (!paper.getCreaterId().equals(currMemberId)) { if(!paper.getCreaterId().equals(currMemberId)) {
return Result.failResult("试卷属于当前用户,不能修改!"); return Result.failResult("试卷属于当前用户,不能修改!");
} }
JSONArray qList = JSONArray.parseArray(paper.getQuestionInfo()); JSONArray qList = JSONArray.parseArray(paper.getQuestionInfo());
for (int i = 0; i < qList.size(); i++) { for(int i =0 ; i<qList.size() ; i++){
JSONObject q = qList.getJSONObject(i); JSONObject q = qList.getJSONObject(i);
if (q.getString("uid").equals(cuid)) { if(q.getString("uid").equals(cuid)){
qList.remove(i); qList.remove(i);
} }
} }
@ -238,34 +167,24 @@ public class PaperServiceImpl extends ServiceImpl<PaperMapper, PaperEntity> impl
return Result.result(Result.SUCCESS_CODE, null, "删除子卷成功"); return Result.result(Result.SUCCESS_CODE, null, "删除子卷成功");
} }
/** @Transactional(readOnly=false)
*
* @param paper
*/
@Transactional(readOnly = false)
@Override @Override
public void addPaper(PaperEntity paper) { public void addPaper(PaperEntity paper) {
paper.setDownHits(0); paper.setDownHits(0);
paper.setOpenHits(0); paper.setOpenHits(0);
paper.setQuestionInfo("[]"); paper.setQuestionInfo("[]");
// 写入 seo 信息 // 写入seo信息
paper.setSeoTitle(paper.getName()); paper.setSeoTitle(paper.getName());
paper.setSeoKeywords(paper.getName()); paper.setSeoKeywords(paper.getName());
paper.setSeoDescription(paper.getName()); paper.setSeoDescription(paper.getName());
paperMapper.insert(paper); paperMapper.insert(paper);
} }
/**
*
* @param paper
* @param currMemberId ID
* @return
*/
@Override @Override
public Result updatePaper(PaperEntity paper, String CurrMemberId) { public Result updatePaper(PaperEntity paper ,String currMemberId) {
PaperEntity entity = paperMapper.selectById(paper.getId()); PaperEntity entity = paperMapper.selectById(paper.getId());
if (!entity.getCreaterId().equals(currMemberId)) { if(!entity.getCreaterId().equals(currMemberId)) {
return Result.failResult("试卷属于当前用户,不能修改!"); return Result.failResult("试卷属于当前用户,不能修改!");
} }
paper.setCreaterId(currMemberId); paper.setCreaterId(currMemberId);
@ -273,19 +192,15 @@ public class PaperServiceImpl extends ServiceImpl<PaperMapper, PaperEntity> impl
return Result.result(Result.SUCCESS_CODE, paper, "修改成功"); return Result.result(Result.SUCCESS_CODE, paper, "修改成功");
} }
/**
*
* @param paperId ID
* @return
*/
@Override @Override
public List<QuestionEntity> findQuestionList(String paperId) { public List<QuestionEntity> findQuestionList(String paperId) {
// 查询选项信息 // 查询选项信息
List<QuestionEntity> questionList = questionMapper.selectList(Condition.create().eq("paper_id", paperId)); List<QuestionEntity> questionList = questionMapper.selectList(Condition.create().eq("paper_id", paperId));
questionList.forEach(question -> { questionList.forEach(question -> {
List<QuestionOptionsEntity> questionOptions = questionOptionsMapper.selectList(Condition.create().eq("question_id", question.getId())); List<QuestionOptionsEntity> questionOptions = questionOptionsMapper.selectList(Condition.create().eq("question_id" , question.getId()));
question.setQuestionOptions(questionOptions); question.setQuestionOptions(questionOptions);
}); });
return questionList; return questionList;
} }
}
}

@ -15,136 +15,67 @@ import com.tamguo.modules.tiku.model.PaperEntity;
import com.tamguo.modules.tiku.model.QuestionEntity; import com.tamguo.modules.tiku.model.QuestionEntity;
import com.tamguo.modules.tiku.service.IQuestionService; import com.tamguo.modules.tiku.service.IQuestionService;
// 标识这是一个Spring的服务层组件类用于实现IQuestionService接口中定义的与题目Question相关的业务逻辑方法
// 它继承自ServicePlus框架提供的ServiceImpl类借助其提供的通用数据库操作能力结合自身的业务逻辑实现对题目数据的添加、查询、更新和删除等操作并且通过依赖注入获取相关的Mapper对象来与数据库进行交互。
@Service @Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, QuestionEntity> implements IQuestionService { public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, QuestionEntity> implements IQuestionService{
// 自动注入PaperMapper用于操作试卷Paper相关的数据比如通过试卷ID查询试卷信息等操作在题目相关业务逻辑中可能需要获取试卷的创建者等信息来进行权限判断等操作依赖该Mapper与数据库的试卷表进行交互。
@Autowired @Autowired
private PaperMapper paperMapper; private PaperMapper paperMapper;
// 自动注入QuestionMapper用于操作题目Question相关的数据比如插入题目、根据条件查询题目、更新题目以及删除题目等数据库操作是实现题目业务逻辑中与数据库进行交互的核心依赖对象直接对应数据库中的题目表。
@Autowired @Autowired
private QuestionMapper questionMapper; private QuestionMapper questionMapper;
/**
*
* ID
* ID
*
* @param question ID
* @param currMemberId IDID
* @return Result0501
*/
@Override @Override
public Result addQuestion(QuestionEntity question, String currMemberId) { public Result addQuestion(QuestionEntity question , String currMemberId) {
// 根据题目实体对象中携带的试卷ID通过PaperMapper从数据库中查询对应的试卷实体信息用于后续判断当前用户对该试卷是否有操作权限即是否为试卷创建者
PaperEntity paper = paperMapper.selectById(question.getPaperId().toString()); PaperEntity paper = paperMapper.selectById(question.getPaperId().toString());
// 判断当前登录会员的ID与查询到的试卷创建者的ID是否相等如果不相等表示当前用户无权操作该试卷下的题目返回包含相应错误提示信息和状态码501的Result对象给调用者。 if(!currMemberId.equals(paper.getCreaterId())) {
if (!currMemberId.equals(paper.getCreaterId())) {
return Result.result(501, null, "改试卷不属于您!"); return Result.result(501, null, "改试卷不属于您!");
} }
// 如果当前用户有权限添加题目将从试卷实体对象中获取的课程ID设置到题目实体对象中保证题目与试卷在课程维度上的关联关系正确便于后续按课程等维度进行题目相关的查询、统计等业务操作。
question.setCourseId(paper.getCourseId()); question.setCourseId(paper.getCourseId());
// 通过QuestionMapper将题目实体对象插入到数据库的题目表中完成题目添加的数据库操作若插入成功则数据库中会新增一条对应的题目记录。
questionMapper.insert(question); questionMapper.insert(question);
// 返回包含添加成功提示信息和状态码0表示成功的Result对象给调用者告知题目添加操作已成功完成。
return Result.result(0, null, "添加成功!"); return Result.result(0, null, "添加成功!");
} }
/**
*
* IDIDID
* IDID
* MyBatis Plus
*
* @param questionType
* @param id IDIDID便ID
* @param content LIKE
* @param paperId IDIDIDID
* @param currMemberId IDID访
* @param p 便
* @return Page<QuestionEntity>p.setRecords(null)
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Page<QuestionEntity> queryQuestionList(String questionType, String id, String content, String paperId, String currMemberId, public Page<QuestionEntity> queryQuestionList(String questionType, String id, String content, String paperId, String currMemberId ,
Page<QuestionEntity> p) { Page<QuestionEntity> p) {
// 根据传入的试卷ID从数据库中查询对应的试卷实体信息然后判断当前登录会员的ID与查询到的试卷创建者的ID是否相等如果不相等表示当前用户无权查询该试卷下的题目直接返回传入的分页对象并将其记录列表设置为空表示无权获取题目数据。 if(!currMemberId.equals(paperMapper.selectById(paperId).getCreaterId())) {
if (!currMemberId.equals(paperMapper.selectById(paperId).getCreaterId())) {
return p.setRecords(null); return p.setRecords(null);
} }
// 创建一个MyBatis Plus的查询条件对象用于构建后续查询题目时的各种条件通过该对象可以方便地添加等于、大于、小于、模糊匹配等各种条件来精确筛选题目数据符合MyBatis Plus的条件查询规范。
Condition condition = new Condition(); Condition condition = new Condition();
// 判断题目类型是否不为空字符串如果不为空则添加一个等于eq条件到查询条件对象中使得查询时只会获取指定题目类型的题目与数据库题目表中的题目类型字段进行精确匹配查询。 if(!StringUtils.isEmpty(questionType)) {
if (!StringUtils.isEmpty(questionType)) {
condition.eq("question_type", questionType); condition.eq("question_type", questionType);
} }
// 判断题目ID是否不为空字符串如果不为空则添加一个等于eq条件到查询条件对象中使得查询时只会获取指定ID的题目与数据库题目表中的题目ID字段进行精确匹配查询用于精确查找特定题目。 if(!StringUtils.isEmpty(id)) {
if (!StringUtils.isEmpty(id)) {
condition.eq("id", id); condition.eq("id", id);
} }
// 判断题目内容是否不为空字符串如果不为空则添加一个模糊匹配like条件到查询条件对象中使得查询时会获取题目内容包含指定关键字的题目通过数据库的模糊查询LIKE操作符与题目表中的题目内容字段进行匹配查询用于根据部分内容查找相关题目。 if(!StringUtils.isEmpty(content)) {
if (!StringUtils.isEmpty(content)) {
condition.like("content", content); condition.like("content", content);
} }
// 添加一个等于eq条件到查询条件对象中指定要查询的题目所属的试卷ID与数据库题目表中的所属试卷ID字段进行精确匹配查询确保获取的题目都是属于指定试卷的。
condition.eq("paper_id", paperId); condition.eq("paper_id", paperId);
// 通过QuestionMapper结合分页对象和构建好的查询条件对象进行分页查询从数据库中获取符合条件的题目列表数据并将查询结果设置到传入的分页对象的记录列表中最后返回该分页对象供前端进行分页展示等操作。
return p.setRecords(questionMapper.selectPage(p, condition)); return p.setRecords(questionMapper.selectPage(p, condition));
} }
/** @Transactional(readOnly=false)
*
* ID
* QuestionMapperID
* 使
*
* @param question ID
* @param currMemberId IDID
* @return Result0501
*/
@Transactional(readOnly = false)
@Override @Override
public Result updateQuestion(QuestionEntity question, String currMemberId) { public Result updateQuestion(QuestionEntity question , String currMemberId) {
// 根据题目实体对象中携带的试卷ID通过PaperMapper从数据库中查询对应的试卷实体信息用于后续判断当前用户对该试卷是否有操作权限即是否为试卷创建者
PaperEntity paper = paperMapper.selectById(question.getPaperId().toString()); PaperEntity paper = paperMapper.selectById(question.getPaperId().toString());
// 判断当前登录会员的ID与查询到的试卷创建者的ID是否相等如果不相等表示当前用户无权操作该试卷下的题目返回包含相应错误提示信息和状态码501的Result对象给调用者。 if(!currMemberId.equals(paper.getCreaterId())) {
if (!currMemberId.equals(paper.getCreaterId())) {
return Result.result(501, null, "改试卷不属于您!"); return Result.result(501, null, "改试卷不属于您!");
} }
// 如果当前用户有权限更新题目通过QuestionMapper根据题目实体对象的ID更新数据库中对应的题目记录将传入的题目实体对象中的属性值覆盖原有记录中的相应属性值完成题目信息的更新操作。
questionMapper.updateById(question); questionMapper.updateById(question);
// 返回包含更新成功提示信息和状态码0表示成功的Result对象给调用者告知题目更新操作已成功完成。
return Result.result(0, null, "修改成功!"); return Result.result(0, null, "修改成功!");
} }
/** @Transactional(readOnly=false)
*
* IDID
* QuestionMapperID
* 使
*
* @param uid IDID
* @param currMemberId IDID
* @return Result0501
*/
@Transactional(readOnly = false)
@Override @Override
public Result delete(String uid, String currMemberId) { public Result delete(String uid , String currMemberId) {
// 根据传入的题目ID通过QuestionMapper从数据库中查询对应的题目实体信息用于获取该题目所属试卷的ID以便后续判断当前用户对该试卷是否有操作权限即是否为试卷创建者
QuestionEntity question = questionMapper.selectById(uid); QuestionEntity question = questionMapper.selectById(uid);
// 根据题目所属试卷的ID通过PaperMapper从数据库中查询对应的试卷实体信息用于后续判断当前用户对该试卷是否有操作权限即是否为试卷创建者
PaperEntity paper = paperMapper.selectById(question.getPaperId().toString()); PaperEntity paper = paperMapper.selectById(question.getPaperId().toString());
// 判断当前登录会员的ID与查询到的试卷创建者的ID是否相等如果不相等表示当前用户无权操作该试卷下的题目返回包含相应错误提示信息和状态码501的Result对象给调用者。 if(!currMemberId.equals(paper.getCreaterId())) {
if (!currMemberId.equals(paper.getCreaterId())) {
return Result.result(501, null, "改试卷不属于您!"); return Result.result(501, null, "改试卷不属于您!");
} }
// 如果当前用户有权限删除题目通过QuestionMapper根据题目ID删除数据库中对应的题目记录完成题目删除的数据库操作从数据库表中移除该题目对应的行数据。
questionMapper.deleteById(uid); questionMapper.deleteById(uid);
// 返回包含删除成功提示信息和状态码0表示成功的Result对象给调用者告知题目删除操作已成功完成。
return Result.result(0, null, "删除成功!"); return Result.result(0, null, "删除成功!");
} }
} }

@ -19,78 +19,51 @@ import com.tamguo.modules.tiku.model.PaperEntity;
import com.tamguo.modules.tiku.model.SchoolEntity; import com.tamguo.modules.tiku.model.SchoolEntity;
import com.tamguo.modules.tiku.service.ISchoolService; import com.tamguo.modules.tiku.service.ISchoolService;
/**
* SchoolServiceImpl ISchoolService
*/
@Service @Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, SchoolEntity> implements ISchoolService { public class SchoolService extends ServiceImpl<SchoolMapper, SchoolEntity> implements ISchoolService {
/**
* SchoolMapper
*/
@Autowired @Autowired
private SchoolMapper schoolMapper; private SchoolMapper schoolMapper;
/**
* PaperMapper
*/
@Autowired @Autowired
private PaperMapper paperMapper; private PaperMapper paperMapper;
/**
* CacheService
*/
@Autowired @Autowired
private CacheService cacheService; private CacheService cacheService;
/**
*
* @param shcoolId ID
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<SchoolEntity> findEliteSchoolPaper(String shcoolId) { public List<SchoolEntity> findEliteSchoolPaper(String shcoolId) {
List<SchoolEntity> schoolList = (List<SchoolEntity>) cacheService.getObject(SystemConstant.ELITE_SCHOOL_PAPER); List<SchoolEntity> schoolList = (List<SchoolEntity>) cacheService.getObject(SystemConstant.ELITE_SCHOOL_PAPER);
// 获取名校试卷 // 获取名校试卷
if (schoolList == null) { if(schoolList == null){
Page<SchoolEntity> page = new Page<>(1, 3); Page<SchoolEntity> page = new Page<>(1 , 3);
schoolList = schoolMapper.selectPage(page, Condition.create().eq("id", shcoolId)); schoolList = schoolMapper.selectPage(page, Condition.create().eq("id", shcoolId));
for (SchoolEntity school : schoolList) { for(SchoolEntity school : schoolList){
Page<PaperEntity> p = new Page<>(1, 3); Page<PaperEntity> p = new Page<>(1 , 3);
List<PaperEntity> paperList = paperMapper.selectPage(p, Condition.create().eq("school_id", school.getId())); List<PaperEntity> paperList = paperMapper.selectPage(p, Condition.create().eq("school_id", school.getId()));
school.setPaperList(paperList); school.setPaperList(paperList);
} }
cacheService.setObject(SystemConstant.ELITE_SCHOOL_PAPER, schoolList, 2 * 60 * 60); cacheService.setObject(SystemConstant.ELITE_SCHOOL_PAPER, schoolList , 2 * 60 * 60);
} }
return schoolList; return schoolList;
} }
/**
*
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<SchoolEntity> findEliteSchool() { public List<SchoolEntity> findEliteSchool() {
List<SchoolEntity> schoolList = (List<SchoolEntity>) cacheService.getObject(SystemConstant.ELITE_PAPER); List<SchoolEntity> schoolList = (List<SchoolEntity>) cacheService.getObject(SystemConstant.ELITE_PAPER);
if (schoolList == null) { if(schoolList == null){
RowBounds row = new RowBounds(1, 6); RowBounds row = new RowBounds(1 , 6);
schoolList = schoolMapper.selectPage(row, Condition.EMPTY); schoolList = schoolMapper.selectPage(row, Condition.EMPTY);
cacheService.setObject(SystemConstant.ELITE_PAPER, schoolList, 2 * 60 * 60); cacheService.setObject(SystemConstant.ELITE_PAPER, schoolList , 2 * 60 * 60);
} }
return schoolList; return schoolList;
} }
/** @Transactional(readOnly=true)
* ID
* @param areaId ID
* @return
*/
@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public List<SchoolEntity> findSchoolByAreaId(String areaId) { public List<SchoolEntity> findSchoolByAreaId(String areaId) {
return schoolMapper.selectList(Condition.create().in("area_id", Arrays.asList(areaId.split(",")))); return schoolMapper.selectList(Condition.create().in("area_id", Arrays.asList(areaId.split(","))));
} }
}
}

@ -19,62 +19,39 @@ import com.tamguo.modules.tiku.model.condition.SubjectCondition;
import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum; import com.tamguo.modules.tiku.model.enums.SubjectStatusEnum;
import com.tamguo.modules.tiku.service.ISubjectService; import com.tamguo.modules.tiku.service.ISubjectService;
/**
* SubjectServiceImpl ISubjectService
*/
@Service @Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity> implements ISubjectService { public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity> implements ISubjectService{
/**
* SubjectMapper
*/
@Autowired @Autowired
private SubjectMapper subjectMapper; private SubjectMapper subjectMapper;
/**
* CourseMapper
*/
@Autowired @Autowired
private CourseMapper courseMapper; private CourseMapper courseMapper;
/** @Transactional(readOnly=false)
*
* @param condition
* @return
*/
@Transactional(readOnly = false)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Page<SubjectEntity> listData(SubjectCondition condition) { public Page<SubjectEntity> listData(SubjectCondition condition) {
Page<SubjectEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize()); Page<SubjectEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize());
Condition query = Condition.create(); Condition query = Condition.create();
if (!StringUtils.isEmpty(condition.getUid())) { if(!StringUtils.isEmpty(condition.getUid())) {
query.eq("uid", condition.getUid()); query.eq("uid", condition.getUid());
} else if (!StringUtils.isEmpty(condition.getName())) { }else if(!StringUtils.isEmpty(condition.getName())) {
query.eq("name", condition.getName()); query.eq("name", condition.getName());
} else if (!StringUtils.isEmpty(condition.getStatus())) { }else if(!StringUtils.isEmpty(condition.getStatus())) {
query.eq("status", condition.getStatus()); query.eq("status", condition.getStatus());
} }
query.ne("status", SubjectStatusEnum.DELETE.getValue()); query.ne("status", SubjectStatusEnum.DELETE.getValue());
return page.setRecords(subjectMapper.selectPage(page, query)); return page.setRecords(subjectMapper.selectPage(page, query));
} }
/** @Transactional(readOnly=false)
*
* @param subject
*/
@Transactional(readOnly = false)
@Override @Override
public void save(SubjectEntity subject) { public void save(SubjectEntity subject) {
subject.setStatus(SubjectStatusEnum.NORMAL); subject.setStatus(SubjectStatusEnum.NORMAL);
subjectMapper.insert(subject); subjectMapper.insert(subject);
} }
/** @Transactional(readOnly=false)
*
* @param subject
*/
@Transactional(readOnly = false)
@Override @Override
public void update(SubjectEntity subject) { public void update(SubjectEntity subject) {
SubjectEntity entity = subjectMapper.selectById(subject.getId()); SubjectEntity entity = subjectMapper.selectById(subject.getId());
@ -87,11 +64,7 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
subjectMapper.updateById(entity); subjectMapper.updateById(entity);
} }
/** @Transactional(readOnly=false)
*
* @param uid
*/
@Transactional(readOnly = false)
@Override @Override
public void enable(String uid) { public void enable(String uid) {
SubjectEntity entity = subjectMapper.selectById(uid); SubjectEntity entity = subjectMapper.selectById(uid);
@ -99,11 +72,7 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
subjectMapper.updateById(entity); subjectMapper.updateById(entity);
} }
/** @Transactional(readOnly=false)
*
* @param uid
*/
@Transactional(readOnly = false)
@Override @Override
public void disabled(String uid) { public void disabled(String uid) {
SubjectEntity entity = subjectMapper.selectById(uid); SubjectEntity entity = subjectMapper.selectById(uid);
@ -111,11 +80,7 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
subjectMapper.updateById(entity); subjectMapper.updateById(entity);
} }
/** @Transactional(readOnly=false)
*
* @param uid
*/
@Transactional(readOnly = false)
@Override @Override
public void delete(String uid) { public void delete(String uid) {
SubjectEntity entity = subjectMapper.selectById(uid); SubjectEntity entity = subjectMapper.selectById(uid);
@ -123,26 +88,22 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
subjectMapper.updateById(entity); subjectMapper.updateById(entity);
} }
/**
*
* @return JSON
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public JSONArray getCourseCascaderTree() { public JSONArray getCourseCascaderTree() {
JSONArray courseTree = new JSONArray(); JSONArray courseTree = new JSONArray();
List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.EMPTY); List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.EMPTY);
for (int i = 0; i < subjectList.size(); i++) { for(int i=0 ; i<subjectList.size() ; i++){
SubjectEntity subject = subjectList.get(i); SubjectEntity subject = subjectList.get(i);
JSONObject node = new JSONObject(); JSONObject node = new JSONObject();
node.put("value", subject.getId()); node.put("value", subject.getId());
node.put("label", subject.getName()); node.put("label", subject.getName());
JSONArray children = new JSONArray(); JSONArray children = new JSONArray();
List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("subject_id", subject.getId())); List<CourseEntity> courseList = courseMapper.selectList(Condition.create().eq("subject_id", subject.getId()));
for (int k = 0; k < courseList.size(); k++) { for(int k=0 ; k<courseList.size() ; k++){
CourseEntity course = courseList.get(k); CourseEntity course = courseList.get(k);
JSONObject no = new JSONObject(); JSONObject no = new JSONObject();
no.put("value", course.getId()); no.put("value", course.getId());
no.put("label", course.getName()); no.put("label", course.getName());
@ -154,17 +115,13 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
return courseTree; return courseTree;
} }
/** @Transactional(readOnly=true)
*
* @return JSON
*/
@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public JSONArray getSubjectTree() { public JSONArray getSubjectTree() {
JSONArray courseTree = new JSONArray(); JSONArray courseTree = new JSONArray();
List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.EMPTY); List<SubjectEntity> subjectList = subjectMapper.selectList(Condition.EMPTY);
for (int i = 0; i < subjectList.size(); i++) { for(int i=0 ; i<subjectList.size() ; i++){
SubjectEntity subject = subjectList.get(i); SubjectEntity subject = subjectList.get(i);
JSONObject node = new JSONObject(); JSONObject node = new JSONObject();
node.put("value", subject.getId()); node.put("value", subject.getId());
@ -173,4 +130,5 @@ public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity
} }
return courseTree; return courseTree;
} }
}
}

Loading…
Cancel
Save