feat(security): 重构安全配置并添加用户认证功能

refactor: 将ResponseMessage移动到config包并增强功能
feat: 添加用户管理相关功能及密码加密配置
fix: 修复HelpController中README文件路径问题
docs: 更新application.properties配置注释
style: 清理无用导入和日志文件
This commit is contained in:
qingfeng1121
2025-10-28 12:47:02 +08:00
parent 9132feb870
commit 5803080352
38 changed files with 2733 additions and 9062 deletions

View File

@@ -1,8 +1,5 @@
package com.qf.myafterprojecy;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
@@ -10,6 +7,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.qf.myafterprojecy.config.ResponseMessage;
@RestControllerAdvice
public class GlobalExceptionHandler {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

View File

@@ -0,0 +1,53 @@
package com.qf.myafterprojecy.config;
import com.qf.myafterprojecy.pojo.Users;
import com.qf.myafterprojecy.repository.UsersRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
/**
* 自定义的UserDetailsService实现
* 用于从数据库加载用户信息进行认证
*/
@Component
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
private UsersRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info("用户登录认证: {}", username);
// 从数据库中查询用户
Users user = usersRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
// 转换用户角色为Spring Security的权限
// 根据role字段的值设置不同的角色权限
String role = "ROLE_USER"; // 默认角色
if (user.getRole() == 1) {
role = "ROLE_ADMIN"; // 管理员角色
}
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(role));
// 返回Spring Security的User对象
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
authorities
);
}
}

View File

@@ -0,0 +1,25 @@
package com.qf.myafterprojecy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 密码编码器配置类
* 用于配置Spring Security使用的密码加密方式
*/
@Configuration
public class PasswordEncoderConfig {
/**
* 创建BCrypt密码编码器
* BCrypt是一种强哈希函数适合密码存储
* @return PasswordEncoder实例
*/
@Bean
public PasswordEncoder passwordEncoder() {
// 强度设置为10这是一个平衡安全性和性能的值
return new BCryptPasswordEncoder(10);
}
}

View File

@@ -0,0 +1,257 @@
package com.qf.myafterprojecy.config;
import lombok.Data;
import org.springframework.http.HttpStatus;
/**
* 通用响应消息类,用于封装接口返回的数据结构
* 遵循RESTful API设计规范提供统一的响应格式
* @param <T> 数据类型可以是任意Java对象
*/
@Data
public class ResponseMessage<T> {
// 状态码,通常用于表示请求的处理结果
private Integer code;
// 响应消息,用于描述请求的处理结果信息
private String message;
// 请求是否成功的标志,根据状态码自动设置
private boolean success;
// 响应数据,泛型类型,支持不同类型的数据
private T data;
/**
* 构造方法,用于创建响应消息对象
* 自动根据状态码设置success字段
* @param code 状态码
* @param message 响应消息
* @param data 响应数据
*/
public ResponseMessage(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
// 自动根据状态码判断是否成功
this.success = code >= 200 && code < 300;
}
/**
* 完整参数的构造方法
* @param code 状态码
* @param message 响应消息
* @param data 响应数据
* @param success 是否成功
*/
public ResponseMessage(Integer code, String message, T data, boolean success) {
this.code = code;
this.message = message;
this.data = data;
this.success = success;
}
// ----------------------------------- 成功响应方法 -----------------------------------
/**
* 创建成功响应,默认消息为"操作成功"
* @param data 响应数据
* @param <T> 数据类型
* @return 成功响应对象
*/
public static <T> ResponseMessage<T> success(T data) {
return new ResponseMessage<>(HttpStatus.OK.value(), "操作成功", data, true);
}
/**
* 创建成功响应,自定义消息
* @param data 响应数据
* @param message 响应消息
* @param <T> 数据类型
* @return 成功响应对象
*/
public static <T> ResponseMessage<T> success(T data, String message) {
return new ResponseMessage<>(HttpStatus.OK.value(), message, data, true);
}
/**
* 创建成功响应,自定义状态码
* @param code 状态码
* @param message 响应消息
* @param data 响应数据
* @param <T> 数据类型
* @return 成功响应对象
*/
public static <T> ResponseMessage<T> successWithCode(Integer code, String message, T data) {
return new ResponseMessage<>(code, message, data, true);
}
/**
* 创建空数据的成功响应
* @param message 响应消息
* @param <T> 数据类型
* @return 成功响应对象
*/
public static <T> ResponseMessage<T> successEmpty(String message) {
return new ResponseMessage<>(HttpStatus.OK.value(), message, null, true);
}
// ----------------------------------- 错误响应方法 -----------------------------------
/**
* 创建错误响应默认状态码500
* @param message 错误消息
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> error(String message) {
return new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null, false);
}
/**
* 创建错误响应,自定义状态码
* @param code 状态码
* @param message 错误消息
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> error(Integer code, String message) {
return new ResponseMessage<>(code, message, null, false);
}
/**
* 创建错误响应,包含错误数据
* @param code 状态码
* @param message 错误消息
* @param data 错误数据
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> errorWithData(Integer code, String message, T data) {
return new ResponseMessage<>(code, message, data, false);
}
/**
* 创建参数错误响应状态码400
* @param message 错误消息
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> badRequest(String message) {
return new ResponseMessage<>(HttpStatus.BAD_REQUEST.value(), message, null, false);
}
/**
* 创建未找到资源响应状态码404
* @param message 错误消息
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> notFound(String message) {
return new ResponseMessage<>(HttpStatus.NOT_FOUND.value(), message, null, false);
}
/**
* 创建权限错误响应状态码403
* @param message 错误消息
* @param <T> 数据类型
* @return 错误响应对象
*/
public static <T> ResponseMessage<T> forbidden(String message) {
return new ResponseMessage<>(HttpStatus.FORBIDDEN.value(), message, null, false);
}
// ----------------------------------- 业务操作响应方法 -----------------------------------
/**
* 创建保存操作响应
* @param success 是否成功
* @param data 响应数据
* @param <T> 数据类型
* @return 操作响应对象
*/
public static <T> ResponseMessage<T> save(boolean success, T data) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "保存成功", data, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "保存失败", null, false);
}
/**
* 创建更新操作响应
* @param success 是否成功
* @param data 响应数据
* @param <T> 数据类型
* @return 操作响应对象
*/
public static <T> ResponseMessage<T> update(boolean success, T data) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "更新成功", data, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "更新失败", null, false);
}
/**
* 创建删除操作响应
* @param success 是否成功
* @param <T> 数据类型
* @return 操作响应对象
*/
public static <T> ResponseMessage<T> delete(boolean success) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "删除成功", null, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null, false);
}
/**
* 创建批量删除操作响应
* @param success 是否成功
* @param deletedCount 删除的数量
* @param <T> 数据类型
* @return 操作响应对象
*/
public static <T> ResponseMessage<T> batchDelete(boolean success, int deletedCount) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "成功删除" + deletedCount + "条数据", null, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "批量删除失败", null, false);
}
/**
* 创建分页查询响应
* @param data 分页数据
* @param message 响应消息
* @param <T> 数据类型
* @return 分页响应对象
*/
public static <T> ResponseMessage<T> page(T data, String message) {
return new ResponseMessage<>(HttpStatus.OK.value(), message, data, true);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@@ -1,21 +1,47 @@
package com.qf.myafterprojecy.config;
import javax.ws.rs.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
/**
* Spring Security配置类
* 用于关闭默认的登录验证功能
* 配置权限管理功能
*/
@Configuration
@EnableWebSecurity
// 启用方法级别的安全控制
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 配置安全过滤器链,允许所有请求通过
* 配置AuthenticationManager Bean
* 使用AuthenticationConfiguration来获取认证管理器这是更现代的方式
*/
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
/**
* 配置安全过滤器链
* @param http HttpSecurity对象用于配置HTTP安全策略
* @return 配置好的SecurityFilterChain对象
* @throws Exception 配置过程中可能出现的异常
@@ -25,16 +51,26 @@ public class SecurityConfig {
http
// 禁用CSRF保护对于API服务通常不需要
.csrf().disable()
// 允许所有请求通过,不需要认证
// 配置URL访问权限
.authorizeRequests()
.anyRequest().permitAll()
// 允许公开访问的路径
// 公开get请求
.antMatchers(HttpMethod.GET,"/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/help/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/category-attributes/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/markdowns/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/articles/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/messages/**").permitAll()
// 公开post请求
.antMatchers(HttpMethod.POST,"/api/messages/**").permitAll()
// 管理员才能访问的路径
.antMatchers("/api/admin/**").hasRole("ADMIN")
// 其他所有请求都需要认证
.anyRequest().authenticated()
.and()
// 禁用表单登录
.formLogin().disable()
// 禁用HTTP基本认证
.httpBasic().disable()
// 禁用会话管理对于无状态API服务
.sessionManagement().disable();
// 配置会话管理,使用无状态会话
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Article;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.ArticleDto;
import com.qf.myafterprojecy.service.imp.IArticleService;
@@ -59,7 +59,7 @@ public class ArticleController {
public ResponseMessage<List<Article>> getArticlesByTitle(@PathVariable String title) {
return articleService.getArticlesByTitle(title);
}
/**
* 根据属性ID获取该属性下的所有文章
* @param attributeId 属性ID

View File

@@ -0,0 +1,125 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 认证控制器
* 处理用户登录相关请求
*/
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@Autowired
private AuthenticationManager authenticationManager;
/**
* 用户登录请求体
*/
static class LoginRequest {
private String username;
private String password;
// getters and setters
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
/**
* 用户登录接口
* @param loginRequest 登录请求参数
* @return 登录结果
*/
@PostMapping("/login")
public ResponseMessage<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
logger.info("用户登录请求: {}", loginRequest.getUsername());
try {
// 创建认证令牌
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
// 执行认证
Authentication authentication = authenticationManager.authenticate(authenticationToken);
// 将认证信息存入上下文
SecurityContextHolder.getContext().setAuthentication(authentication);
// 获取认证后的用户信息
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// 构建返回数据
Map<String, Object> data = new HashMap<>();
data.put("username", userDetails.getUsername());
data.put("authorities", userDetails.getAuthorities());
data.put("message", "登录成功");
return ResponseMessage.success(data, "登录成功");
} catch (AuthenticationException e) {
logger.error("登录失败: {}", e.getMessage());
return ResponseMessage.error("用户名或密码错误");
}
}
/**
* 获取当前登录用户信息
* @return 当前用户信息
*/
@PostMapping("/info")
public ResponseMessage<Map<String, Object>> getCurrentUserInfo() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return ResponseMessage.error("未登录");
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Map<String, Object> data = new HashMap<>();
data.put("username", userDetails.getUsername());
data.put("authorities", userDetails.getAuthorities());
return ResponseMessage.success(data, "获取用户信息成功");
}
/**
* 用户登出接口
* @return 登出结果
*/
@PostMapping("/logout")
public ResponseMessage<Void> logout() {
SecurityContextHolder.clearContext();
return ResponseMessage.successEmpty("登出成功");
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category_attribute;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryAttributeDto;
import com.qf.myafterprojecy.service.imp.ICategoryAttributeService;

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryDto;
import com.qf.myafterprojecy.service.imp.ICategoryService;

View File

@@ -1,6 +1,5 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
@@ -10,6 +9,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qf.myafterprojecy.config.ResponseMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -30,35 +31,31 @@ public class HelpController {
@GetMapping
public ResponseMessage<String> getReadmeApi() {
try {
// 获取README_API.md文件的绝对路径
String readmePath = "e:\\MyWebProject\\MyAfterProjecy\\README_API.md";
File readmeFile = new File(readmePath);
// 获取项目根目录
String rootPath = System.getProperty("user.dir") ;
// 构建README_API.md文件路径
File readmeFile = new File(rootPath, "README_API.md");
// 检查文件是否存在
if (readmeFile.exists() && readmeFile.isFile()) {
// 读取文件内容
String markdownContent = new String(FileCopyUtils.copyToByteArray(new FileInputStream(readmeFile)), StandardCharsets.UTF_8);
// 将Markdown转换为HTML
String htmlContent = convertMarkdownToHtml(markdownContent);
return ResponseMessage.success(htmlContent, "获取API文档成功");
if (!readmeFile.exists() || !readmeFile.isFile()) {
// 如果不存在,尝试使用类路径资源加载
try {
ClassPathResource resource = new ClassPathResource("README_API.md");
String markdownContent = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()), StandardCharsets.UTF_8);
// 将Markdown转换为HTML
String htmlContent = convertMarkdownToHtml(markdownContent);
return ResponseMessage.success(htmlContent, "获取API文档成功");
} catch (IOException e) {
return ResponseMessage.error("未找到README_API.md文件");
}
}
// 如果直接路径不存在,尝试从类路径加载
try {
ClassPathResource resource = new ClassPathResource("README_API.md");
String markdownContent = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()), StandardCharsets.UTF_8);
// 将Markdown转换为HTML
String htmlContent = convertMarkdownToHtml(markdownContent);
return ResponseMessage.success(htmlContent, "获取API文档成功");
} catch (IOException e) {
// 记录详细错误信息以便调试
System.err.println("无法从类路径加载README_API.md: " + e.getMessage());
return ResponseMessage.error("未找到README_API.md文件");
}
} catch (Exception e) {
// 捕获所有异常并记录详细错误信息
System.err.println("处理README_API.md时出错: " + e.getMessage());
e.printStackTrace();
// 读取文件内容
String markdownContent = new String(FileCopyUtils.copyToByteArray(new FileInputStream(readmeFile)), StandardCharsets.UTF_8);
// 将Markdown转换为HTML
// String htmlContent = convertMarkdownToHtml(markdownContent);
return ResponseMessage.success(markdownContent, "获取API文档成功");
} catch (IOException e) {
return ResponseMessage.error("读取README_API.md文件失败: " + e.getMessage());
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Message;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.MessageDto;
import com.qf.myafterprojecy.service.imp.IMessageService;

View File

@@ -0,0 +1,134 @@
package com.qf.myafterprojecy.controller;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Users;
import com.qf.myafterprojecy.pojo.dto.UserDto;
import com.qf.myafterprojecy.service.imp.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private IUserService userService;
/**
* 根据ID获取用户信息
* @param id 用户ID
* @return 用户信息
*/
@GetMapping("/{id}")
public ResponseMessage<Users> getUserById(@PathVariable Long id) {
logger.info("获取用户信息用户ID: {}", id);
return userService.getUserById(id);
}
/**
* 获取所有用户列表
* @return 用户列表
*/
@GetMapping
public ResponseMessage<List<Users>> getAllUsers() {
logger.info("获取所有用户列表");
return userService.getAllUsers();
}
/**
* 根据用户名获取用户信息
* @param username 用户名
* @return 用户信息
*/
@GetMapping("/username/{username}")
public ResponseMessage<Users> getUserByUsername(@PathVariable String username) {
logger.info("根据用户名获取用户信息,用户名: {}", username);
return userService.getUserByUsername(username);
}
/**
* 创建新用户
* @param userDto 用户数据
* @return 创建结果
*/
@PostMapping
public ResponseMessage<Users> saveUser(@Valid @RequestBody UserDto userDto) {
logger.info("创建新用户,用户名: {}", userDto.getUsername());
return userService.saveUser(userDto);
}
/**
* 更新用户信息
* @param id 用户ID
* @param userDto 用户数据
* @return 更新结果
*/
@PutMapping("/{id}")
public ResponseMessage<Users> updateUser(@PathVariable Long id, @Valid @RequestBody UserDto userDto) {
logger.info("更新用户信息用户ID: {}", id);
return userService.updateUser(id, userDto);
}
/**
* 删除用户
* @param id 用户ID
* @return 删除结果
*/
@DeleteMapping("/{id}")
public ResponseMessage<Boolean> deleteUser(@PathVariable Long id) {
logger.info("删除用户用户ID: {}", id);
return userService.deleteUser(id);
}
/**
* 根据角色查询用户列表
* @param role 角色
* @return 用户列表
*/
@GetMapping("/role/{role}")
public ResponseMessage<List<Users>> getUsersByRole(@PathVariable int role) {
logger.info("根据角色查询用户列表,角色: {}", role);
return userService.getUsersByRole(role);
}
/**
* 检查用户名是否存在
* @param username 用户名
* @return 是否存在
*/
@GetMapping("/check/username/{username}")
public ResponseMessage<Boolean> existsByUsername(@PathVariable String username) {
logger.info("检查用户名是否存在,用户名: {}", username);
return userService.existsByUsername(username);
}
/**
* 检查邮箱是否存在
* @param email 邮箱
* @return 是否存在
*/
@GetMapping("/check/email/{email}")
public ResponseMessage<Boolean> existsByEmail(@PathVariable String email) {
logger.info("检查邮箱是否存在,邮箱: {}", email);
return userService.existsByEmail(email);
}
/**
* 检查手机号是否存在
* @param phone 手机号
* @return 是否存在
*/
@GetMapping("/check/phone/{phone}")
public ResponseMessage<Boolean> existsByPhone(@PathVariable String phone) {
logger.info("检查手机号是否存在,手机号: {}", phone);
return userService.existsByPhone(phone);
}
}

View File

@@ -39,9 +39,14 @@ public class Article {
@Column(name = "likes")
private Integer likes; // 点赞数
@Column(name = "status")
private Integer status; // 0-草稿1-已发布2-已删除
@Column(name = "markdownscontent")
@NotBlank(message = "Markdown内容不能为空")
private String markdownscontent;
// Getters and Setters
public Integer getLikes() {
@@ -125,4 +130,12 @@ public class Article {
public void setViewCount(Integer viewCount) {
this.viewCount = viewCount;
}
public String getMarkdownscontent() {
return markdownscontent;
}
public void setMarkdownscontent(String markdownscontent) {
this.markdownscontent = markdownscontent;
}
}

View File

@@ -1,128 +0,0 @@
package com.qf.myafterprojecy.pojo;
import lombok.Data;
import org.springframework.http.HttpStatus;
/**
* 通用响应消息类,用于封装接口返回的数据结构
* 使用泛型T来支持不同类型的数据返回
* @param <T> 数据类型可以是任意Java对象
*/
@Data
public class ResponseMessage<T> {
// 状态码,通常用于表示请求的处理结果
private Integer code;
// 响应消息,用于描述请求的处理结果信息
private String message;
// 请求是否成功的标志
private boolean success;
// 响应数据,泛型类型,支持不同类型的数据
private T data;
/**
* 构造方法,用于创建响应消息对象
* @param code 状态码
* @param message 响应消息
* @param data 响应数据
*/
public ResponseMessage(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
// 获取成功状态的getter方法
public boolean isSuccess() {
return success;
}
// 设置成功状态的setter方法
public void setSuccess(boolean success) {
this.success = success;
}
// 获取状态码的getter方法
public Integer getCode() {
return code;
}
// 设置状态码的setter方法
public void setCode(Integer code) {
this.code = code;
}
// 获取响应消息的getter方法
public String getMessage() {
return message;
}
// 设置响应消息的setter方法
public void setMessage(String message) {
this.message = message;
}
// 获取响应数据的getter方法
public T getData() {
return data;
}
// 设置响应数据的setter方法
public void setData(T data) {
this.data = data;
}
/**
* 完整参数的构造方法
* @param code 状态码
* @param message 响应消息
* @param data 响应数据
* @param success 是否成功
*/
public ResponseMessage(Integer code, String message, T data, boolean success) {
this.code = code;
this.message = message;
this.data = data;
this.success = success;
}
// 接口请求成功
public static <T> ResponseMessage<T> success(T data ,String message ,boolean success) {
return new ResponseMessage(HttpStatus.OK.value(), message, data ,success);
}
/**
* 创建一个表示操作失败的响应消息
* @param message 失败原因的描述信息
* @return 返回一个包含错误状态码和错误信息的ResponseMessage对象
*/
public static <T> ResponseMessage<T> failure(String message) {
return new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null, false);
}
public static <T> ResponseMessage<T> success(T data) {
return new ResponseMessage<>(HttpStatus.OK.value(), "操作成功", data, true);
}
public static <T> ResponseMessage<T> success(T data, String message) {
return new ResponseMessage<>(HttpStatus.OK.value(), message, data, true);
}
public static <T> ResponseMessage<T> error(String message) {
return new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null, false);
}
public static <T> ResponseMessage<T> error(Integer code, String message) {
return new ResponseMessage<>(code, message, null, false);
}
public static <T> ResponseMessage<T> Save(boolean success) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "保存成功", null, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "保存失败", null, false);
}
public static <T> ResponseMessage<T> Delete(boolean success) {
return success ?
new ResponseMessage<>(HttpStatus.OK.value(), "删除成功", null, true) :
new ResponseMessage<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null, false);
}
}

View File

@@ -0,0 +1,89 @@
package com.qf.myafterprojecy.pojo;
import java.time.LocalDateTime;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@Entity
@Table(name = "users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, unique = true)
private Long id;
@NotBlank(message = "用户名不能为空")
@Column(name = "username", nullable = false, unique = true)
private String username;
@NotBlank(message = "密码不能为空")
@Column(name = "password", nullable = false)
private String password;
@NotBlank(message = "邮箱不能为空")
@Column(name = "email", nullable = false, unique = true)
private String email;
@NotBlank(message = "手机号不能为空")
@Column(name = "phone", nullable = false, unique = true)
private String phone;
@Column(name = "role", nullable = false)
private int role;
@Column(name = "create_time", nullable = false)
private LocalDateTime createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
}

View File

@@ -0,0 +1,20 @@
package com.qf.myafterprojecy.pojo.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class MarkdownDto {
@NotBlank(message = "Markdown内容不能为空")
private String markdownscontent;
public String getMarkdownscontent() {
return markdownscontent;
}
public void setMarkdownscontent(String markdownscontent) {
this.markdownscontent = markdownscontent;
}
}

View File

@@ -0,0 +1,61 @@
package com.qf.myafterprojecy.pojo.dto;
import javax.validation.constraints.NotBlank;
public class UserDto {
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
private String password;
@NotBlank(message = "邮箱不能为空")
private String email;
@NotBlank(message = "手机号不能为空")
private String phone;
@NotBlank(message = "角色不能为空")
private int role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
}

View File

@@ -0,0 +1,63 @@
package com.qf.myafterprojecy.repository;
import com.qf.myafterprojecy.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
@Repository
public interface UsersRepository extends JpaRepository<Users, Long> {
/**
* 根据用户名查询用户信息
* @param username 用户名
* @return 返回符合条件的用户对象
*/
Optional<Users> findByUsername(String username);
/**
* 根据邮箱查询用户信息
* @param email 邮箱
* @return 返回符合条件的用户对象
*/
Optional<Users> findByEmail(String email);
/**
* 根据手机号查询用户信息
* @param phone 手机号
* @return 返回符合条件的用户对象
*/
Optional<Users> findByPhone(String phone);
/**
* 检查用户名是否存在
* @param username 用户名
* @return 返回是否存在
*/
boolean existsByUsername(String username);
/**
* 检查邮箱是否存在
* @param email 邮箱
* @return 返回是否存在
*/
boolean existsByEmail(String email);
/**
* 检查手机号是否存在
* @param phone 手机号
* @return 返回是否存在
*/
boolean existsByPhone(String phone);
/**
* 根据角色查询用户列表
* @param role 角色
* @return 用户列表
*/
@Query("SELECT u FROM Users u WHERE u.role = :role")
java.util.List<Users> findByRole(@Param("role") int role);
}

View File

@@ -1,169 +0,0 @@
package com.qf.myafterprojecy.runner;
import com.qf.myafterprojecy.pojo.Message;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.MessageDto;
import com.qf.myafterprojecy.repository.MessageRepository;
import com.qf.myafterprojecy.service.imp.IMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Optional;
/**
* 消息数据检查器,用于验证消息相关的业务代码是否正常工作
*/
@Component
public class MessageDataChecker implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(MessageDataChecker.class);
@Autowired
private MessageRepository messageRepository;
@Autowired
private IMessageService messageService;
@Override
public void run(String... args) throws Exception {
logger.info("===== 消息数据检查器开始运行 =====");
// 检查数据库中是否已有消息数据
long count = messageRepository.count();
logger.info("当前数据库中消息数量: {}", count);
// 如果没有消息数据,添加一些测试数据
if (count == 0) {
logger.info("数据库中没有消息数据,开始添加测试数据...");
addTestMessages();
}
// 测试查询方法
testQueryMethods();
// 测试服务层方法
testServiceMethods();
logger.info("===== 消息数据检查器运行结束 =====");
}
private void addTestMessages() {
// 添加第一篇文章的评论
Message message1 = new Message();
message1.setNickname("张三");
message1.setEmail("zhangsan@example.com");
message1.setContent("这是一篇很棒的文章!");
message1.setCreatedAt(new Date());
message1.setArticleid(1);
message1.setParentid(null); // 根评论
message1.setLikes(0); // 设置点赞数初始值为0
messageRepository.save(message1);
// 添加回复
Message reply1 = new Message();
reply1.setNickname("李四");
reply1.setEmail("lisi@example.com");
reply1.setContent("同意你的观点!");
reply1.setCreatedAt(new Date());
reply1.setArticleid(1);
reply1.setParentid(message1.getMessageid()); // 回复第一篇评论
reply1.setLikes(0); // 设置点赞数初始值为0
messageRepository.save(reply1);
// 添加第二篇文章的评论
Message message2 = new Message();
message2.setNickname("王五");
message2.setEmail("wangwu@example.com");
message2.setContent("学到了很多东西,谢谢分享!");
message2.setCreatedAt(new Date());
message2.setArticleid(2);
message2.setParentid(null);
message2.setLikes(0); // 设置点赞数初始值为0
messageRepository.save(message2);
logger.info("成功添加了{}条测试消息数据", messageRepository.count());
}
private void testQueryMethods() {
logger.info("===== 测试Repository查询方法 =====");
// 测试根据文章ID查询
List<Message> article1Messages = messageRepository.findByArticleid(1);
logger.info("文章ID为1的消息数量: {}", article1Messages.size());
// 测试查询所有根消息
List<Message> rootMessages = messageRepository.findByParentidIsNull();
logger.info("根消息数量: {}", rootMessages.size());
// 测试根据昵称模糊查询
List<Message> zhangMessages = messageRepository.findByNicknameContaining("");
logger.info("昵称包含'张'的消息数量: {}", zhangMessages.size());
// 测试统计文章评论数量
Long article1Count = messageRepository.countByArticleId(1);
logger.info("文章ID为1的评论数量: {}", article1Count);
// 如果有根消息,测试查询回复
if (!rootMessages.isEmpty()) {
Integer firstRootId = rootMessages.get(0).getMessageid();
List<Message> replies = messageRepository.findByParentid(firstRootId);
logger.info("消息ID为{}的回复数量: {}", firstRootId, replies.size());
}
}
private void testServiceMethods() {
logger.info("===== 测试Service层方法 =====");
// 测试获取所有消息
ResponseMessage<Iterable<Message>> allMessagesResponse = messageService.getAllMessages();
logger.info("获取所有消息: 成功={}, 消息数量={}", allMessagesResponse.isSuccess(),
((List<Message>)allMessagesResponse.getData()).size());
// 测试根据ID获取消息
if (messageRepository.count() > 0) {
Message firstMessage = messageRepository.findAll().iterator().next();
Integer messageId = firstMessage.getMessageid();
ResponseMessage<Message> messageResponse = messageService.getMessageById(messageId);
logger.info("根据ID{}获取消息: 成功={}, 昵称={}", messageId,
messageResponse.isSuccess(),
messageResponse.getData() != null ? messageResponse.getData().getNickname() : "null");
// 测试获取指定文章的评论数量
ResponseMessage<Long> countResponse = messageService.getMessageCountByArticleId(1);
logger.info("获取文章ID为1的评论数量: 成功={}, 数量={}",
countResponse.isSuccess(), countResponse.getData());
// 测试获取根消息
ResponseMessage<List<Message>> rootResponse = messageService.getRootMessages();
logger.info("获取根消息: 成功={}, 数量={}",
rootResponse.isSuccess(),
rootResponse.getData() != null ? rootResponse.getData().size() : 0);
}
// 测试保存新消息
MessageDto newMessage = new MessageDto();
newMessage.setNickname("测试用户");
newMessage.setEmail("test@example.com");
newMessage.setContent("这是一条测试消息");
newMessage.setArticleid(1);
newMessage.setParentid(null);
ResponseMessage<Message> saveResponse = messageService.saveMessage(newMessage);
logger.info("保存新消息: 成功={}, 消息ID={}",
saveResponse.isSuccess(),
saveResponse.getData() != null ? saveResponse.getData().getMessageid() : "null");
// 如果保存成功,测试删除
if (saveResponse.isSuccess() && saveResponse.getData() != null) {
Integer savedId = saveResponse.getData().getMessageid();
ResponseMessage<Message> deleteResponse = messageService.deleteMessage(savedId);
logger.info("删除消息ID{}: 成功={}", savedId, deleteResponse.isSuccess());
}
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Article;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.ArticleDto;
import com.qf.myafterprojecy.repository.ArticleRepository;
import com.qf.myafterprojecy.repository.CategoryAttributeRepository;
@@ -34,18 +34,25 @@ public class ArticleService implements IArticleService {
public ResponseMessage<Article> getArticleById(String id) {
try {
if (id == null || id.isEmpty()) {
return ResponseMessage.failure("文章ID不能为空");
return ResponseMessage.badRequest("文章ID不能为空");
}
Article article = articleRepository.findById(Integer.parseInt(id))
.orElseThrow(() -> new RuntimeException("文章不存在"));
// 暂时不增加浏览次数,以避免事务问题
// articleRepository.incrementViewCount(id);
return ResponseMessage.success(article);
// articleRepository.incrementViewCount(Integer.parseInt(id));
return ResponseMessage.success(article, "获取文章成功");
} catch (NumberFormatException e) {
return ResponseMessage.badRequest("文章ID格式不正确");
} catch (RuntimeException e) {
if (e.getMessage().contains("文章不存在")) {
return ResponseMessage.notFound("文章不存在");
}
log.error("获取文章失败: {}", e.getMessage());
return ResponseMessage.error("获取文章失败");
} catch (Exception e) {
log.error("获取文章失败: {}", e.getMessage());
return ResponseMessage.failure("获取文章失败");
return ResponseMessage.error("获取文章失败");
}
}
/**
@@ -57,10 +64,10 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getPublishedArticles() {
try {
List<Article> articles = articleRepository.findByStatus(1);
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "获取已发布文章列表成功");
} catch (Exception e) {
log.error("获取已发布文章列表失败: {}", e.getMessage());
return ResponseMessage.failure("获取已发布文章列表失败");
return ResponseMessage.error("获取已发布文章列表失败");
}
}
@Override
@@ -68,13 +75,13 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getArticlesByTitle(String title) {
try {
if (title == null || title.isEmpty()) {
return ResponseMessage.failure("文章标题不能为空");
return ResponseMessage.badRequest("文章标题不能为空");
}
List<Article> articles = articleRepository.findByTitle(title);
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "根据标题查询文章成功");
} catch (Exception e) {
log.error("根据标题查询文章列表失败: {}", e.getMessage());
return ResponseMessage.failure("根据标题查询文章列表失败");
return ResponseMessage.error("根据标题查询文章列表失败");
}
}
@@ -83,10 +90,10 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getAllArticles() {
try {
List<Article> articles = articleRepository.findAll();
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "获取文章列表成功");
} catch (DataAccessException e) {
log.error("获取文章列表失败: {}", e.getMessage());
return ResponseMessage.failure("获取文章列表失败");
return ResponseMessage.error("获取文章列表失败");
}
}
@@ -102,10 +109,10 @@ public class ArticleService implements IArticleService {
article.setStatus(articleDto.getStatus() != null ? articleDto.getStatus() : 0);
Article savedArticle = articleRepository.save(article);
return ResponseMessage.success(savedArticle);
return ResponseMessage.save(true, savedArticle);
} catch (DataAccessException e) {
log.error("保存文章失败: {}", e.getMessage());
return ResponseMessage.failure("保存文章失败");
return ResponseMessage.error("保存文章失败");
}
}
@@ -120,10 +127,16 @@ public class ArticleService implements IArticleService {
article.setUpdatedAt(LocalDateTime.now());
Article updatedArticle = articleRepository.save(article);
return ResponseMessage.success(updatedArticle);
return ResponseMessage.update(true, updatedArticle);
} catch (RuntimeException e) {
if (e.getMessage().contains("文章不存在")) {
return ResponseMessage.notFound("文章不存在");
}
log.error("更新文章失败: {}", e.getMessage());
return ResponseMessage.error("更新文章失败");
} catch (Exception e) {
log.error("更新文章失败: {}", e.getMessage());
return ResponseMessage.failure("更新文章失败");
return ResponseMessage.error("更新文章失败");
}
}
@@ -138,10 +151,16 @@ public class ArticleService implements IArticleService {
article.setUpdatedAt(LocalDateTime.now());
articleRepository.save(article);
return ResponseMessage.success(null);
return ResponseMessage.delete(true);
} catch (RuntimeException e) {
if (e.getMessage().contains("文章不存在")) {
return ResponseMessage.notFound("文章不存在");
}
log.error("删除文章失败: {}", e.getMessage());
return ResponseMessage.error("删除文章失败");
} catch (Exception e) {
log.error("删除文章失败: {}", e.getMessage());
return ResponseMessage.failure("删除文章失败");
return ResponseMessage.error("删除文章失败");
}
}
@@ -153,10 +172,10 @@ public class ArticleService implements IArticleService {
// 旧接口使用typeid但我们现在用attributeid
// 可以考虑查询该分类下的所有属性,然后获取相关文章
log.warn("使用了旧接口getArticlesByCategory请考虑迁移到getArticlesByAttribute");
return ResponseMessage.success(articleRepository.findPublishedByAttribute(categoryId));
return ResponseMessage.success(articleRepository.findPublishedByAttribute(categoryId), "获取分类文章成功");
} catch (DataAccessException e) {
log.error("获取分类文章失败: {}", e.getMessage());
return ResponseMessage.failure("获取分类文章失败");
return ResponseMessage.error("获取分类文章失败");
}
}
@@ -165,19 +184,19 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getArticlesByAttribute(Integer attributeid) {
try {
if (attributeid == null || attributeid <= 0) {
return ResponseMessage.failure("属性ID无效");
return ResponseMessage.badRequest("属性ID无效");
}
// 验证属性是否存在
if (!categoryAttributeRepository.existsById(attributeid)) {
return ResponseMessage.failure("属性不存在");
return ResponseMessage.notFound("属性不存在");
}
List<Article> articles = articleRepository.findPublishedByAttribute(attributeid);
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "获取属性文章成功");
} catch (DataAccessException e) {
log.error("获取属性文章失败: {}", e.getMessage());
return ResponseMessage.failure("获取属性文章失败");
return ResponseMessage.error("获取属性文章失败");
}
}
@@ -196,10 +215,16 @@ public class ArticleService implements IArticleService {
articleRepository.incrementViewCount(id);
return ResponseMessage.success(article);
return ResponseMessage.success(article, "增加文章浏览量成功");
} catch (RuntimeException e) {
if (e.getMessage().contains("文章不存在")) {
return ResponseMessage.notFound("文章不存在");
}
log.error("增加文章浏览量失败: {}", e.getMessage());
return ResponseMessage.error("增加文章浏览量失败");
} catch (Exception e) {
log.error("增加文章浏览量失败: {}", e.getMessage());
return ResponseMessage.failure("增加文章浏览量失败");
return ResponseMessage.error("增加文章浏览量失败");
}
}
@@ -208,19 +233,19 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getLatestArticlesByAttribute(Integer attributeid) {
try {
if (attributeid == null || attributeid <= 0) {
return ResponseMessage.failure("属性ID无效");
return ResponseMessage.badRequest("属性ID无效");
}
// 验证属性是否存在
if (!categoryAttributeRepository.existsById(attributeid)) {
return ResponseMessage.failure("属性不存在");
return ResponseMessage.notFound("属性不存在");
}
List<Article> articles = articleRepository.findLatestByAttribute(attributeid);
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "获取最新属性文章成功");
} catch (DataAccessException e) {
log.error("获取最新属性文章失败: {}", e.getMessage());
return ResponseMessage.failure("获取最新属性文章失败");
return ResponseMessage.error("获取最新属性文章失败");
}
}
@@ -229,10 +254,10 @@ public class ArticleService implements IArticleService {
public ResponseMessage<List<Article>> getMostViewedArticles() {
try {
List<Article> articles = articleRepository.findMostViewed();
return ResponseMessage.success(articles);
return ResponseMessage.success(articles, "获取热门文章成功");
} catch (DataAccessException e) {
log.error("获取热门文章失败: {}", e.getMessage());
return ResponseMessage.failure("获取热门文章失败");
return ResponseMessage.error("获取热门文章失败");
}
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category_attribute;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryAttributeDto;
import com.qf.myafterprojecy.repository.CategoryAttributeRepository;
import com.qf.myafterprojecy.service.imp.ICategoryAttributeService;
@@ -29,16 +29,22 @@ public class CategoryAttributeService implements ICategoryAttributeService {
public ResponseMessage<Category_attribute> getCategoryAttributeById(Integer id) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("属性ID无效");
return ResponseMessage.badRequest("属性ID无效");
}
Category_attribute attribute = categoryAttributeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("分类属性不存在"));
return ResponseMessage.success(attribute);
return ResponseMessage.success(attribute, "获取分类属性成功");
} catch (RuntimeException e) {
if (e.getMessage().contains("分类属性不存在")) {
return ResponseMessage.notFound("分类属性不存在");
}
log.error("获取分类属性失败: {}", e.getMessage());
return ResponseMessage.error("获取分类属性失败");
} catch (Exception e) {
log.error("获取分类属性失败: {}", e.getMessage());
return ResponseMessage.failure("获取分类属性失败");
return ResponseMessage.error("获取分类属性失败");
}
}
@@ -47,14 +53,14 @@ public class CategoryAttributeService implements ICategoryAttributeService {
public ResponseMessage<List<Category_attribute>> getAttributesByCategoryId(Integer categoryId) {
try {
if (categoryId == null || categoryId <= 0) {
return ResponseMessage.failure("分类ID无效");
return ResponseMessage.badRequest("分类ID无效");
}
List<Category_attribute> attributes = categoryAttributeRepository.findByCategoryId(categoryId);
return ResponseMessage.success(attributes);
return ResponseMessage.success(attributes, "获取分类属性列表成功");
} catch (DataAccessException e) {
log.error("获取分类属性列表失败: {}", e.getMessage());
return ResponseMessage.failure("获取分类属性列表失败");
return ResponseMessage.error("获取分类属性列表失败");
}
}
@@ -65,7 +71,7 @@ public class CategoryAttributeService implements ICategoryAttributeService {
// 检查属性名称是否已存在于该分类下
if (categoryAttributeRepository.existsByCategoryidAndAttributename(
dto.getCategoryid(), dto.getAttributename())) {
return ResponseMessage.failure("该分类下已存在同名属性");
return ResponseMessage.badRequest("该分类下已存在同名属性");
}
Category_attribute attribute = new Category_attribute();
@@ -75,10 +81,10 @@ public class CategoryAttributeService implements ICategoryAttributeService {
log.info("成功创建分类属性: {}, 分类ID: {}",
savedAttribute.getAttributename(), savedAttribute.getCategoryid());
return ResponseMessage.success(savedAttribute);
return ResponseMessage.save(true, savedAttribute);
} catch (DataAccessException e) {
log.error("保存分类属性失败: {}", e.getMessage());
return ResponseMessage.failure("保存分类属性失败");
return ResponseMessage.error("保存分类属性失败");
}
}
@@ -87,7 +93,7 @@ public class CategoryAttributeService implements ICategoryAttributeService {
public ResponseMessage<Category_attribute> updateCategoryAttribute(Integer id, CategoryAttributeDto dto) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("属性ID无效");
return ResponseMessage.badRequest("属性ID无效");
}
Category_attribute attribute = categoryAttributeRepository.findById(id)
@@ -97,7 +103,7 @@ public class CategoryAttributeService implements ICategoryAttributeService {
if (!attribute.getAttributename().equals(dto.getAttributename()) &&
categoryAttributeRepository.existsByCategoryidAndAttributename(
dto.getCategoryid(), dto.getAttributename())) {
return ResponseMessage.failure("该分类下已存在同名属性");
return ResponseMessage.badRequest("该分类下已存在同名属性");
}
BeanUtils.copyProperties(dto, attribute);
@@ -107,10 +113,16 @@ public class CategoryAttributeService implements ICategoryAttributeService {
log.info("成功更新分类属性: ID={}, 名称={}",
updatedAttribute.getAttributeid(), updatedAttribute.getAttributename());
return ResponseMessage.success(updatedAttribute);
return ResponseMessage.update(true, updatedAttribute);
} catch (RuntimeException e) {
if (e.getMessage().contains("分类属性不存在")) {
return ResponseMessage.notFound("分类属性不存在");
}
log.error("更新分类属性失败: {}", e.getMessage());
return ResponseMessage.error("更新分类属性失败");
} catch (Exception e) {
log.error("更新分类属性失败: {}", e.getMessage());
return ResponseMessage.failure("更新分类属性失败");
return ResponseMessage.error("更新分类属性失败");
}
}
@@ -119,20 +131,20 @@ public class CategoryAttributeService implements ICategoryAttributeService {
public ResponseMessage<Boolean> deleteCategoryAttribute(Integer id) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("属性ID无效");
return ResponseMessage.badRequest("属性ID无效");
}
if (!categoryAttributeRepository.existsById(id)) {
return ResponseMessage.failure("分类属性不存在");
return ResponseMessage.notFound("分类属性不存在");
}
categoryAttributeRepository.deleteById(id);
log.info("成功删除分类属性: ID={}", id);
return ResponseMessage.success(true);
return ResponseMessage.delete(true);
} catch (Exception e) {
log.error("删除分类属性失败: {}", e.getMessage());
return ResponseMessage.failure("删除分类属性失败");
return ResponseMessage.error("删除分类属性失败");
}
}
@@ -141,16 +153,16 @@ public class CategoryAttributeService implements ICategoryAttributeService {
public ResponseMessage<Boolean> existsByCategoryAndName(Integer categoryId, String attributeName) {
try {
if (categoryId == null || categoryId <= 0 || attributeName == null || attributeName.isEmpty()) {
return ResponseMessage.failure("参数无效");
return ResponseMessage.badRequest("参数无效");
}
boolean exists = categoryAttributeRepository.existsByCategoryidAndAttributename(
categoryId, attributeName);
return ResponseMessage.success(exists);
return ResponseMessage.success(exists, "检查分类属性成功");
} catch (DataAccessException e) {
log.error("检查分类属性是否存在失败: {}", e.getMessage());
return ResponseMessage.failure("检查分类属性是否存在失败");
return ResponseMessage.error("检查分类属性是否存在失败");
}
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryDto;
import com.qf.myafterprojecy.repository.CategoryRepository;
import com.qf.myafterprojecy.service.imp.ICategoryService;
@@ -30,14 +30,20 @@ public class CategoryService implements ICategoryService {
public ResponseMessage<Category> getCategoryById(Integer id) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("分类ID无效");
return ResponseMessage.badRequest("分类ID无效");
}
Category category = categoryRepository.findById(id)
.orElseThrow(() -> new RuntimeException("分类不存在"));
return ResponseMessage.success(category);
return ResponseMessage.success(category, "获取分类成功");
} catch (RuntimeException e) {
if (e.getMessage().contains("分类不存在")) {
return ResponseMessage.notFound("分类不存在");
}
log.error("获取分类失败: {}", e.getMessage());
return ResponseMessage.error("获取分类失败");
} catch (Exception e) {
log.error("获取分类失败: {}", e.getMessage());
return ResponseMessage.failure("获取分类失败");
return ResponseMessage.error("获取分类失败");
}
}
@@ -46,10 +52,10 @@ public class CategoryService implements ICategoryService {
public ResponseMessage<List<Category>> getAllCategories() {
try {
List<Category> categories = categoryRepository.findAll();
return ResponseMessage.success(categories);
return ResponseMessage.success(categories, "获取分类列表成功");
} catch (DataAccessException e) {
log.error("获取分类列表失败: {}", e.getMessage());
return ResponseMessage.failure("获取分类列表失败");
return ResponseMessage.error("获取分类列表失败");
}
}
@@ -59,7 +65,7 @@ public class CategoryService implements ICategoryService {
try {
// 检查分类名称是否已存在
if (categoryRepository.existsByTypename(categoryDto.getTypename())) {
return ResponseMessage.failure("分类名称已存在");
return ResponseMessage.badRequest( "分类名称已存在");
}
Category category = new Category();
@@ -68,10 +74,10 @@ public class CategoryService implements ICategoryService {
category.setUpdatedAt(LocalDateTime.now());
Category savedCategory = categoryRepository.save(category);
return ResponseMessage.success(savedCategory);
return ResponseMessage.save(true, savedCategory);
} catch (DataAccessException e) {
log.error("保存分类失败: {}", e.getMessage());
return ResponseMessage.failure("保存分类失败");
return ResponseMessage.error("保存分类失败");
}
}
@@ -80,7 +86,7 @@ public class CategoryService implements ICategoryService {
public ResponseMessage<Category> updateCategory(Integer id, CategoryDto categoryDto) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("分类ID无效");
return ResponseMessage.badRequest("分类ID无效");
}
Category category = categoryRepository.findById(id)
@@ -89,17 +95,23 @@ public class CategoryService implements ICategoryService {
// 如果修改了分类名称,检查新名称是否已存在
if (!category.getTypename().equals(categoryDto.getTypename()) &&
categoryRepository.existsByTypename(categoryDto.getTypename())) {
return ResponseMessage.failure("分类名称已存在");
return ResponseMessage.badRequest("分类名称已存在");
}
BeanUtils.copyProperties(categoryDto, category);
category.setUpdatedAt(LocalDateTime.now());
Category updatedCategory = categoryRepository.save(category);
return ResponseMessage.success(updatedCategory);
return ResponseMessage.update(true, updatedCategory);
} catch (RuntimeException e) {
if (e.getMessage().contains("分类不存在")) {
return ResponseMessage.notFound("分类不存在");
}
log.error("更新分类失败: {}", e.getMessage());
return ResponseMessage.error("更新分类失败");
} catch (Exception e) {
log.error("更新分类失败: {}", e.getMessage());
return ResponseMessage.failure("更新分类失败");
return ResponseMessage.error("更新分类失败");
}
}
@@ -108,20 +120,20 @@ public class CategoryService implements ICategoryService {
public ResponseMessage<Boolean> deleteCategory(Integer id) {
try {
if (id == null || id <= 0) {
return ResponseMessage.failure("分类ID无效");
return ResponseMessage.badRequest("分类ID无效");
}
if (!categoryRepository.existsById(id)) {
return ResponseMessage.failure("分类不存在");
return ResponseMessage.notFound("分类不存在");
}
// 注意:实际项目中可能需要先检查是否有文章引用该分类
// 如果有,可能需要先处理文章或者禁止删除
categoryRepository.deleteById(id);
return ResponseMessage.success(true);
return ResponseMessage.delete(true);
} catch (Exception e) {
log.error("删除分类失败: {}", e.getMessage());
return ResponseMessage.failure("删除分类失败");
return ResponseMessage.error("删除分类失败");
}
}
@@ -130,14 +142,14 @@ public class CategoryService implements ICategoryService {
public ResponseMessage<List<Category>> searchCategoriesByTypename(String typename) {
try {
if (typename == null || typename.trim().isEmpty()) {
return ResponseMessage.failure("分类名称不能为空");
return ResponseMessage.badRequest("分类名称不能为空");
}
List<Category> categories = categoryRepository.findByTypenameContaining(typename);
return ResponseMessage.success(categories);
return ResponseMessage.success(categories, "搜索分类成功");
} catch (DataAccessException e) {
log.error("搜索分类失败: {}", e.getMessage());
return ResponseMessage.failure("搜索分类失败");
return ResponseMessage.error("搜索分类失败");
}
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Message;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.MessageDto;
import com.qf.myafterprojecy.repository.MessageRepository;
import com.qf.myafterprojecy.service.imp.IMessageService;
@@ -33,10 +33,10 @@ public class MessageService implements IMessageService {
try {
logger.info("查询所有消息");
Iterable<Message> messages = messageRepository.findAll();
return ResponseMessage.success(messages, "查询成功", true);
return ResponseMessage.success(messages, "查询成功");
} catch (DataAccessException e) {
logger.error("查询所有消息失败", e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -44,21 +44,21 @@ public class MessageService implements IMessageService {
public ResponseMessage<Message> getMessageById(Integer id) {
if (id == null || id <= 0) {
logger.warn("获取消息时ID无效: {}", id);
return ResponseMessage.failure("消息ID无效");
return ResponseMessage.badRequest("消息ID无效");
}
try {
logger.info("根据ID查询消息: {}", id);
Optional<Message> messageOptional = messageRepository.findById(id);
if (messageOptional.isPresent()) {
return ResponseMessage.success(messageOptional.get(), "查询成功", true);
return ResponseMessage.success(messageOptional.get(), "查询成功");
} else {
logger.warn("未找到ID为{}的消息", id);
return ResponseMessage.failure("未找到指定消息");
return ResponseMessage.notFound("未找到指定消息");
}
} catch (DataAccessException e) {
logger.error("查询消息失败: {}", id, e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -94,16 +94,15 @@ public class MessageService implements IMessageService {
if (messageDto.getParentid() != null && messageDto.getParentid() > 0) {
if (!messageRepository.existsById(messageDto.getParentid())) {
logger.warn("回复的父消息不存在: {}", messageDto.getParentid());
return ResponseMessage.failure("回复的父消息不存在");
return ResponseMessage.notFound("回复的父消息不存在");
}
}
Message savedMessage = messageRepository.save(message);
logger.info("消息保存成功: {}", savedMessage.getMessageid());
return ResponseMessage.success(savedMessage, "保存成功", true);
return ResponseMessage.save(true, savedMessage);
} catch (DataAccessException e) {
logger.error("保存消息失败", e);
return ResponseMessage.failure("保存消息失败:" + e.getMessage());
return ResponseMessage.error("保存消息失败:" + e.getMessage());
}
}
@@ -112,7 +111,7 @@ public class MessageService implements IMessageService {
public ResponseMessage<Message> deleteMessage(Integer id) {
if (id == null || id <= 0) {
logger.warn("删除消息时ID无效: {}", id);
return ResponseMessage.failure("消息ID无效");
return ResponseMessage.badRequest("消息ID无效");
}
try {
@@ -126,14 +125,14 @@ public class MessageService implements IMessageService {
logger.info("同时删除了{}条回复消息", replies.size());
}
logger.info("消息删除成功: {}", id);
return ResponseMessage.success(null, "删除成功", true);
return ResponseMessage.delete(true);
} else {
logger.warn("未找到要删除的消息: {}", id);
return ResponseMessage.failure("未找到要删除的消息");
return ResponseMessage.notFound("未找到要删除的消息");
}
} catch (DataAccessException e) {
logger.error("删除消息失败: {}", id, e);
return ResponseMessage.failure("删除消息失败:" + e.getMessage());
return ResponseMessage.error("删除消息失败:" + e.getMessage());
}
}
@@ -141,16 +140,16 @@ public class MessageService implements IMessageService {
public ResponseMessage<List<Message>> getMessagesByArticleId(Integer articleId) {
if (articleId == null || articleId <= 0) {
logger.warn("根据文章ID查询消息时ID无效: {}", articleId);
return ResponseMessage.failure("文章ID无效");
return ResponseMessage.badRequest("文章ID无效");
}
try {
logger.info("根据文章ID查询消息: {}", articleId);
List<Message> messages = messageRepository.findByArticleid(articleId);
return ResponseMessage.success(messages, "查询成功", true);
return ResponseMessage.success(messages, "查询成功");
} catch (DataAccessException e) {
logger.error("根据文章ID查询消息失败: {}", articleId, e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -159,10 +158,10 @@ public class MessageService implements IMessageService {
try {
logger.info("查询所有根消息");
List<Message> messages = messageRepository.findByParentidIsNull();
return ResponseMessage.success(messages, "查询成功", true);
return ResponseMessage.success(messages, "查询成功");
} catch (DataAccessException e) {
logger.error("查询根消息失败", e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -170,15 +169,15 @@ public class MessageService implements IMessageService {
public ResponseMessage<List<Message>> getRepliesByParentId(Integer parentId) {
if (parentId == null || parentId <= 0) {
logger.warn("根据父消息ID查询回复时ID无效: {}", parentId);
return ResponseMessage.failure("父消息ID无效");
return ResponseMessage.badRequest("父消息ID无效");
}
try {
logger.info("根据父消息ID查询回复: {}", parentId);
List<Message> replies = messageRepository.findByParentid(parentId);
return ResponseMessage.success(replies, "查询成功", true);
return ResponseMessage.success(replies, "查询成功");
} catch (DataAccessException e) {
logger.error("查询回复消息失败: {}", parentId, e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -188,16 +187,16 @@ public class MessageService implements IMessageService {
public ResponseMessage<Message> likeMessage(Integer id) {
if (id == null || id <= 0) {
logger.warn("点赞消息时ID无效: {}", id);
return ResponseMessage.failure("消息ID无效");
return ResponseMessage.badRequest("消息ID无效");
}
try {
logger.info("点赞消息: {}", id);
messageRepository.incrementLikes(id);
Message likedMessage = messageRepository.findById(id).orElse(null);
return ResponseMessage.success(likedMessage, "点赞成功", true);
return ResponseMessage.success(likedMessage, "点赞成功");
} catch (DataAccessException e) {
logger.error("点赞消息失败: {}", id, e);
return ResponseMessage.failure("点赞消息失败:" + e.getMessage());
return ResponseMessage.error("点赞消息失败:" + e.getMessage());
}
}
@@ -205,16 +204,16 @@ public class MessageService implements IMessageService {
public ResponseMessage<List<Message>> searchMessagesByNickname(String nickname) {
if (StringUtils.isEmpty(nickname)) {
logger.warn("根据昵称查询消息时昵称为空");
return ResponseMessage.failure("昵称不能为空");
return ResponseMessage.badRequest("昵称不能为空");
}
try {
logger.info("根据昵称查询消息: {}", nickname);
List<Message> messages = messageRepository.findByNicknameContaining(nickname);
return ResponseMessage.success(messages, "查询成功", true);
return ResponseMessage.success(messages, "查询成功");
} catch (DataAccessException e) {
logger.error("根据昵称查询消息失败: {}", nickname, e);
return ResponseMessage.failure("查询消息失败:" + e.getMessage());
return ResponseMessage.error("查询消息失败:" + e.getMessage());
}
}
@@ -225,10 +224,10 @@ public class MessageService implements IMessageService {
try {
logger.info("删除所有消息");
messageRepository.deleteAll();
return ResponseMessage.success(null, "删除成功", true);
return ResponseMessage.delete(true);
} catch (DataAccessException e) {
logger.error("删除所有消息失败", e);
return ResponseMessage.failure("删除消息失败:" + e.getMessage());
return ResponseMessage.error("删除消息失败:" + e.getMessage());
}
}
@@ -236,16 +235,16 @@ public class MessageService implements IMessageService {
public ResponseMessage<Long> getMessageCountByArticleId(Integer articleId) {
if (articleId == null || articleId <= 0) {
logger.warn("获取文章评论数量时ID无效: {}", articleId);
return ResponseMessage.failure("文章ID无效");
return ResponseMessage.badRequest("文章ID无效");
}
try {
logger.info("获取文章评论数量: {}", articleId);
Long count = messageRepository.countByArticleId(articleId);
return ResponseMessage.success(count, "查询成功", true);
return ResponseMessage.success(count, "查询成功");
} catch (DataAccessException e) {
logger.error("获取文章评论数量失败: {}", articleId, e);
return ResponseMessage.failure("查询评论数量失败:" + e.getMessage());
return ResponseMessage.error("查询评论数量失败:" + e.getMessage());
}
}
}

View File

@@ -0,0 +1,236 @@
package com.qf.myafterprojecy.service;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Users;
import com.qf.myafterprojecy.pojo.dto.UserDto;
import com.qf.myafterprojecy.repository.UsersRepository;
import com.qf.myafterprojecy.service.imp.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Service
public class UserService implements IUserService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
private UsersRepository usersRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public ResponseMessage<Users> getUserById(Long id) {
try {
Optional<Users> userOptional = usersRepository.findById(id);
if (userOptional.isPresent()) {
return ResponseMessage.success(userOptional.get(), "获取用户成功");
} else {
return ResponseMessage.notFound("用户不存在");
}
} catch (DataAccessException e) {
logger.error("获取用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("获取用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<List<Users>> getAllUsers() {
try {
List<Users> users = usersRepository.findAll();
return ResponseMessage.success(users, "获取所有用户成功");
} catch (DataAccessException e) {
logger.error("获取所有用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("获取所有用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<Users> getUserByUsername(String username) {
try {
Optional<Users> userOptional = usersRepository.findByUsername(username);
if (userOptional.isPresent()) {
return ResponseMessage.success(userOptional.get(), "获取用户成功");
} else {
return ResponseMessage.notFound("用户不存在");
}
} catch (DataAccessException e) {
logger.error("根据用户名获取用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("根据用户名获取用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Transactional
@Override
public ResponseMessage<Users> saveUser(UserDto userDto) {
try {
// 检查用户名是否已存在
if (usersRepository.existsByUsername(userDto.getUsername())) {
return ResponseMessage.badRequest("用户名已存在");
}
// 检查邮箱是否已存在
if (usersRepository.existsByEmail(userDto.getEmail())) {
return ResponseMessage.badRequest("邮箱已存在");
}
// 检查手机号是否已存在
if (usersRepository.existsByPhone(userDto.getPhone())) {
return ResponseMessage.badRequest("手机号已存在");
}
// 创建新用户
Users user = new Users();
BeanUtils.copyProperties(userDto, user);
// 使用密码编码器加密密码
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setCreateTime(LocalDateTime.now());
// 保存用户
Users savedUser = usersRepository.save(user);
return ResponseMessage.save(true, savedUser);
} catch (DataAccessException e) {
logger.error("保存用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("保存用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Transactional
@Override
public ResponseMessage<Users> updateUser(Long id, UserDto userDto) {
try {
Optional<Users> userOptional = usersRepository.findById(id);
if (!userOptional.isPresent()) {
return ResponseMessage.notFound("用户不存在");
}
Users user = userOptional.get();
// 检查用户名是否被其他用户使用
if (!user.getUsername().equals(userDto.getUsername()) && usersRepository.existsByUsername(userDto.getUsername())) {
return ResponseMessage.badRequest("用户名已存在");
}
// 检查邮箱是否被其他用户使用
if (!user.getEmail().equals(userDto.getEmail()) && usersRepository.existsByEmail(userDto.getEmail())) {
return ResponseMessage.badRequest("邮箱已存在");
}
// 检查手机号是否被其他用户使用
if (!user.getPhone().equals(userDto.getPhone()) && usersRepository.existsByPhone(userDto.getPhone())) {
return ResponseMessage.badRequest("手机号已存在");
}
// 更新用户信息
BeanUtils.copyProperties(userDto, user);
// 保存更新后的用户
Users updatedUser = usersRepository.save(user);
return ResponseMessage.update(true, updatedUser);
} catch (DataAccessException e) {
logger.error("更新用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("更新用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Transactional
@Override
public ResponseMessage<Boolean> deleteUser(Long id) {
try {
if (!usersRepository.existsById(id)) {
return ResponseMessage.notFound("用户不存在");
}
usersRepository.deleteById(id);
return ResponseMessage.delete(true);
} catch (DataAccessException e) {
logger.error("删除用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("删除用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<List<Users>> getUsersByRole(int role) {
try {
List<Users> users = usersRepository.findByRole(role);
return ResponseMessage.success(users, "根据角色获取用户成功");
} catch (DataAccessException e) {
logger.error("根据角色获取用户异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("根据角色获取用户未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<Boolean> existsByUsername(String username) {
try {
boolean exists = usersRepository.existsByUsername(username);
return ResponseMessage.success(exists, "查询成功");
} catch (DataAccessException e) {
logger.error("检查用户名存在性异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("检查用户名存在性未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<Boolean> existsByEmail(String email) {
try {
boolean exists = usersRepository.existsByEmail(email);
return ResponseMessage.success(exists, "查询成功");
} catch (DataAccessException e) {
logger.error("检查邮箱存在性异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("检查邮箱存在性未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
@Override
public ResponseMessage<Boolean> existsByPhone(String phone) {
try {
boolean exists = usersRepository.existsByPhone(phone);
return ResponseMessage.success(exists, "查询成功");
} catch (DataAccessException e) {
logger.error("检查手机号存在性异常: {}", e.getMessage());
return ResponseMessage.error("数据库访问异常");
} catch (Exception e) {
logger.error("检查手机号存在性未知异常: {}", e.getMessage());
return ResponseMessage.error("服务器异常");
}
}
}

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service.imp;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Article;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.ArticleDto;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service.imp;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category_attribute;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryAttributeDto;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service.imp;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Category;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.CategoryDto;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.myafterprojecy.service.imp;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Message;
import com.qf.myafterprojecy.pojo.ResponseMessage;
import com.qf.myafterprojecy.pojo.dto.MessageDto;
import java.util.List;

View File

@@ -0,0 +1,79 @@
package com.qf.myafterprojecy.service.imp;
import com.qf.myafterprojecy.config.ResponseMessage;
import com.qf.myafterprojecy.pojo.Users;
import com.qf.myafterprojecy.pojo.dto.UserDto;
import java.util.List;
public interface IUserService {
/**
* 根据ID获取用户信息
* @param id 用户ID
* @return 返回用户信息
*/
ResponseMessage<Users> getUserById(Long id);
/**
* 获取所有用户列表
* @return 返回用户列表
*/
ResponseMessage<List<Users>> getAllUsers();
/**
* 根据用户名获取用户信息
* @param username 用户名
* @return 返回用户信息
*/
ResponseMessage<Users> getUserByUsername(String username);
/**
* 保存新用户
* @param userDto 用户数据传输对象
* @return 返回保存结果
*/
ResponseMessage<Users> saveUser(UserDto userDto);
/**
* 更新用户信息
* @param id 用户ID
* @param userDto 用户数据传输对象
* @return 返回更新结果
*/
ResponseMessage<Users> updateUser(Long id, UserDto userDto);
/**
* 删除用户
* @param id 用户ID
* @return 返回删除结果
*/
ResponseMessage<Boolean> deleteUser(Long id);
/**
* 根据角色查询用户列表
* @param role 角色
* @return 用户列表
*/
ResponseMessage<List<Users>> getUsersByRole(int role);
/**
* 检查用户名是否存在
* @param username 用户名
* @return 是否存在
*/
ResponseMessage<Boolean> existsByUsername(String username);
/**
* 检查邮箱是否存在
* @param email 邮箱
* @return 是否存在
*/
ResponseMessage<Boolean> existsByEmail(String email);
/**
* 检查手机号是否存在
* @param phone 手机号
* @return 是否存在
*/
ResponseMessage<Boolean> existsByPhone(String phone);
}