refactor:

This commit is contained in:
Hvemi_han 2025-03-26 09:28:29 +08:00
parent 0fc9b4545c
commit 6974aab6c4
16 changed files with 111 additions and 111 deletions

View File

@ -17,28 +17,28 @@ public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiResponse<Void> handleEntityNotFoundException(EntityNotFoundException e) {
logger.error("Entity not found: {}", e.getMessage());
// logger.error("Entity not found: {}", e.getMessage());
return ApiResponse.error(10003, e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<Void> handleIllegalArgumentException(IllegalArgumentException e) {
logger.error("Invalid argument: {}", e.getMessage());
// logger.error("Invalid argument: {}", e.getMessage());
return ApiResponse.error(10001, e.getMessage());
}
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("Invalid request body: {}", e.getMessage());
// logger.error("Invalid request body: {}", e.getMessage());
return ApiResponse.error(10001, "请求体格式不正确");
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiResponse<Void> handleException(Exception e) {
logger.error("Unexpected error: ", e);
// logger.error("Unexpected error: ", e);
return ApiResponse.error(10009, "系统错误");
}
}

View File

@ -37,7 +37,7 @@ public class RedisConfig {
if (redisPassword != null && !redisPassword.isEmpty()) {
config.setPassword(redisPassword);
}
logger.info("Configuring Redis connection to {}:{}", redisHost, redisPort);
// logger.info("Configuring Redis connection to {}:{}", redisHost, redisPort);
return new LettuceConnectionFactory(config);
}
@ -74,9 +74,9 @@ public class RedisConfig {
// 测试连接
try {
template.getConnectionFactory().getConnection().ping();
logger.info("Redis连接测试成功");
// logger.info("Redis连接测试成功");
} catch (Exception e) {
logger.error("Redis连接测试失败: {}", e.getMessage(), e);
// logger.error("Redis连接测试失败: {}", e.getMessage(), e);
}
return template;

View File

@ -30,24 +30,24 @@ public class LessonTaskController {
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size,
@RequestParam(required = false) Long userId) {
logger.info("收到课程任务列表查询请求,页码: {},每页数量: {}用户ID: {}", page, size, userId);
// logger.info("收到课程任务列表查询请求,页码: {},每页数量: {}用户ID: {}", page, size, userId);
try {
Page<LessonTask> tasks = lessonTaskService.findAll(PageRequest.of(page - 1, size), userId);
return ApiResponse.success(tasks);
} catch (Exception e) {
logger.error("查询课程任务列表失败", e);
// logger.error("查询课程任务列表失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务列表失败", null);
}
}
@GetMapping("/{id}")
public ApiResponse<LessonTask> getTask(@PathVariable Long id) {
logger.info("收到课程任务查询请求任务ID: {}", id);
// logger.info("收到课程任务查询请求任务ID: {}", id);
try {
LessonTask task = lessonTaskService.findById(id);
return ApiResponse.success(task);
} catch (Exception e) {
logger.error("查询课程任务失败", e);
// logger.error("查询课程任务失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务失败", null);
}
}
@ -57,49 +57,49 @@ public class LessonTaskController {
@PathVariable Long departmentId,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
logger.info("收到部门课程任务查询请求部门ID: {}", departmentId);
// logger.info("收到部门课程任务查询请求部门ID: {}", departmentId);
try {
PageRequest pageRequest = PageRequest.of(page - 1, size);
Page<LessonTaskDTO> tasks = lessonTaskService.findByDepartmentIdAndNormalUser(departmentId, pageRequest);
return ApiResponse.success(tasks);
} catch (Exception e) {
logger.error("查询部门课程任务失败", e);
// logger.error("查询部门课程任务失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门课程任务失败", null);
}
}
@PostMapping
public ApiResponse<LessonTask> createTask(@Valid @RequestBody LessonTaskRequest request) {
logger.info("收到创建课程任务请求");
// logger.info("收到创建课程任务请求");
try {
LessonTask task = lessonTaskService.create(request);
return ApiResponse.success(task);
} catch (Exception e) {
logger.error("创建课程任务失败", e);
// logger.error("创建课程任务失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "创建课程任务失败", null);
}
}
@PutMapping("/{id}")
public ApiResponse<LessonTask> updateTask(@PathVariable Long id, @Valid @RequestBody LessonTaskRequest request) {
logger.info("收到更新课程任务请求任务ID: {}", id);
// logger.info("收到更新课程任务请求任务ID: {}", id);
try {
LessonTask task = lessonTaskService.update(id, request);
return ApiResponse.success(task);
} catch (Exception e) {
logger.error("更新课程任务失败", e);
// logger.error("更新课程任务失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "更新课程任务失败", null);
}
}
@DeleteMapping("/{id}")
public ApiResponse<Void> deleteTask(@PathVariable Long id) {
logger.info("收到删除课程任务请求任务ID: {}", id);
// logger.info("收到删除课程任务请求任务ID: {}", id);
try {
lessonTaskService.delete(id);
return ApiResponse.success();
} catch (Exception e) {
logger.error("删除课程任务失败", e);
// logger.error("删除课程任务失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "删除课程任务失败", null);
}
}

View File

@ -38,9 +38,9 @@ public class UserController {
@PostMapping("/login")
public ApiResponse<LoginResponse> login(@Valid @RequestBody UserLoginRequest request) {
logger.info("收到登录请求,邮箱: {}", request.getEmail());
// logger.info("收到登录请求,邮箱: {}", request.getEmail());
ApiResponse<LoginResponse> response = userService.login(request);
logger.info("登录响应: {}", response);
// logger.info("登录响应: {}", response);
return response;
}
@ -59,19 +59,19 @@ public class UserController {
@PostMapping
public ApiResponse<Void> createUser(@Valid @RequestBody CreateUserRequest request) {
logger.info("收到创建用户请求,用户名: {}", request.getUsername());
// logger.info("收到创建用户请求,用户名: {}", request.getUsername());
return userService.createUser(request);
}
@GetMapping("/current")
public ApiResponse<User> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
logger.info("收到获取当前用户信息请求Authorization: {}", authHeader);
// logger.info("收到获取当前用户信息请求Authorization: {}", authHeader);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
logger.info("解析出的token: {}", token);
// logger.info("解析出的token: {}", token);
return userService.getCurrentUser(token);
}
logger.warn("未提供有效的认证令牌");
// logger.warn("未提供有效的认证令牌");
return ApiResponse.error(401, "未提供有效的认证令牌");
}
@ -79,37 +79,37 @@ public class UserController {
public ApiResponse<?> listUsers(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer limit) {
logger.info("收到用户列表分页查询请求,页码: {},每页数量: {}", page, limit);
// logger.info("收到用户列表分页查询请求,页码: {},每页数量: {}", page, limit);
return userService.listUsers(page, limit);
}
@PostMapping("/disable/{userId}")
public ApiResponse<String> disableUser(@PathVariable Long userId) {
logger.info("收到禁用用户请求用户ID: {}", userId);
// logger.info("收到禁用用户请求用户ID: {}", userId);
return userService.disableUser(userId);
}
@GetMapping("/department/{departmentId}")
public ApiResponse<List<User>> getUsersByDepartment(@PathVariable Long departmentId) {
logger.info("收到查询部门用户请求部门ID: {}", departmentId);
// logger.info("收到查询部门用户请求部门ID: {}", departmentId);
try {
List<User> users = userService.findByDepartmentId(departmentId);
// 清除密码信息
users.forEach(user -> user.setPassword(null));
return ApiResponse.success(users);
} catch (Exception e) {
logger.error("查询部门用户失败", e);
// logger.error("查询部门用户失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门用户列表失败", null);
}
}
@GetMapping("/teacher/search")
public ApiResponse<User> searchTeacher(@RequestParam String email) {
logger.info("收到查询教师信息请求,邮箱: {}", email);
// logger.info("收到查询教师信息请求,邮箱: {}", email);
try {
return userService.findTeacherByEmail(email);
} catch (Exception e) {
logger.error("查询教师信息失败", e);
// logger.error("查询教师信息失败", e);
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "查询教师信息失败", null);
}
}

View File

@ -49,21 +49,21 @@ public class LessonTask implements Serializable {
@PrePersist
protected void onCreate() {
logger.info("创建新课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
this.courseName, this.microLessonName, this.userId);
// logger.info("创建新课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
// this.courseName, this.microLessonName, this.userId);
progressStatus = 0;
long now = System.currentTimeMillis() / 1000;
createdAt = now;
updatedAt = now;
logger.info("创建课程任务成功 - 进度状态: {}, 创建时间: {}, 更新时间: {}",
progressStatus, createdAt, updatedAt);
// logger.info("创建课程任务成功 - 进度状态: {}, 创建时间: {}, 更新时间: {}",
// progressStatus, createdAt, updatedAt);
}
@PreUpdate
protected void onUpdate() {
logger.info("更新课程任务 - ID: {}, 课程名称: {}, 微课名称: {}",
this.id, this.courseName, this.microLessonName);
// logger.info("更新课程任务 - ID: {}, 课程名称: {}, 微课名称: {}",
// this.id, this.courseName, this.microLessonName);
updatedAt = System.currentTimeMillis() / 1000;
logger.info("更新课程任务成功 - ID: {}, 更新时间: {}", id, updatedAt);
// logger.info("更新课程任务成功 - ID: {}, 更新时间: {}", id, updatedAt);
}
}

View File

@ -25,15 +25,15 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
logger.info("Loading user details for email: {}", email);
// logger.info("Loading user details for email: {}", email);
User user = userRepository.findByEmail(email)
.orElseThrow(() -> {
logger.error("User not found with email: {}", email);
// logger.error("User not found with email: {}", email);
return new UsernameNotFoundException("User not found with email: " + email);
});
logger.info("User found with email: {}", email);
// logger.info("User found with email: {}", email);
return new org.springframework.security.core.userdetails.User(
user.getEmail(),

View File

@ -51,29 +51,29 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
try {
// 允许OPTIONS请求通过
if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
logger.debug("OPTIONS请求直接放行");
// logger.debug("OPTIONS请求直接放行");
filterChain.doFilter(request, response);
return;
}
final String authHeader = request.getHeader("Authorization");
logger.debug("处理请求认证 - 请求路径: {}", request.getRequestURI());
// logger.debug("处理请求认证 - 请求路径: {}", request.getRequestURI());
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
logger.debug("未提供认证令牌或格式不正确");
// logger.debug("未提供认证令牌或格式不正确");
filterChain.doFilter(request, response);
return;
}
final String jwt = authHeader.substring(7);
logger.debug("Received JWT token: {}", jwt);
// logger.debug("Received JWT token: {}", jwt);
final String username = jwtService.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
logger.debug("开始验证用户令牌 - 用户邮箱: {}", username);
// logger.debug("开始验证用户令牌 - 用户邮箱: {}", username);
if (tokenBlacklistService.isBlacklisted(jwt)) {
logger.warn("令牌已被加入黑名单");
// logger.warn("令牌已被加入黑名单");
handleJwtException(response, "令牌已被加入黑名单");
return;
}
@ -81,7 +81,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtService.isTokenValid(jwt, userDetails)) {
logger.debug("令牌验证成功,设置安全上下文");
// logger.debug("令牌验证成功,设置安全上下文");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
@ -89,7 +89,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
} else {
logger.warn("令牌验证失败");
// logger.warn("令牌验证失败");
handleJwtException(response, "令牌验证失败");
return;
}

View File

@ -48,8 +48,8 @@ public class JwtService {
public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {
Date issuedAt = new Date(System.currentTimeMillis() / 1000 * 1000);
Date expiration = new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000);
logger.debug("Generating token for user: {}, expiration: {}, jwtExpiration: {}", userDetails.getUsername(),
expiration, jwtExpiration);
// logger.debug("Generating token for user: {}, expiration: {}, jwtExpiration: {}", userDetails.getUsername(),
// expiration, jwtExpiration);
return Jwts.builder()
.setClaims(extraClaims)

View File

@ -25,18 +25,18 @@ public class TokenBlacklistService {
* @param expiration 过期时间
*/
public void addToBlacklist(String token, long expiration) {
logger.info("将令牌加入黑名单 - 过期时间: {}", new Date(expiration * 1000));
// logger.info("将令牌加入黑名单 - 过期时间: {}", new Date(expiration * 1000));
try {
String key = BLACKLIST_PREFIX + token;
long ttl = expiration - System.currentTimeMillis() / 1000;
if (ttl > 0) {
redisTemplate.opsForValue().set(key, "blacklisted", ttl, TimeUnit.SECONDS);
logger.info("令牌已成功加入黑名单");
// logger.info("令牌已成功加入黑名单");
} else {
logger.warn("令牌已过期,无需加入黑名单");
// logger.warn("令牌已过期,无需加入黑名单");
}
} catch (Exception e) {
logger.error("将令牌加入黑名单时发生错误", e);
// logger.error("将令牌加入黑名单时发生错误", e);
throw new RuntimeException("无法将令牌加入黑名单", e);
}
}
@ -48,14 +48,14 @@ public class TokenBlacklistService {
* @return 如果在黑名单中返回true
*/
public boolean isBlacklisted(String token) {
logger.debug("检查令牌是否在黑名单中");
// logger.debug("检查令牌是否在黑名单中");
try {
String key = BLACKLIST_PREFIX + token;
Boolean exists = redisTemplate.hasKey(key);
logger.debug("令牌黑名单检查结果: {}", exists);
// logger.debug("令牌黑名单检查结果: {}", exists);
return Boolean.TRUE.equals(exists);
} catch (Exception e) {
logger.error("检查令牌黑名单状态时发生错误", e);
// logger.error("检查令牌黑名单状态时发生错误", e);
return false;
}
}

View File

@ -19,15 +19,15 @@ public class UserDetailsService implements org.springframework.security.core.use
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
logger.info("开始加载用户信息 - 邮箱: {}", email);
// logger.info("开始加载用户信息 - 邮箱: {}", email);
User user = userRepository.findByEmail(email)
.orElseThrow(() -> {
logger.error("未找到用户 - 邮箱: {}", email);
// logger.error("未找到用户 - 邮箱: {}", email);
return new UsernameNotFoundException("未找到用户");
});
logger.info("成功加载用户信息 - 用户名: {}", user.getUsername());
// logger.info("成功加载用户信息 - 用户名: {}", user.getUsername());
return user;
}
}

View File

@ -56,7 +56,7 @@ public class DepartmentService {
departmentRepository.save(department);
successCount++;
} catch (Exception e) {
logger.error("导入第{}行数据失败", i + 2, e);
// logger.error("导入第{}行数据失败", i + 2, e);
errorMsg.append(String.format("第%d行导入失败;", i + 2));
}
}

View File

@ -36,8 +36,8 @@ public class LessonTaskService {
@Cacheable(value = "lessonTasks", key = "#userId != null ? 'user:' + #userId + ':page:' + #pageable.pageNumber : 'all:page:' + #pageable.pageNumber")
public Page<LessonTask> findAll(Pageable pageable, Long userId) {
logger.info("查询课程任务 - 页码: {}, 每页数量: {}, 用户ID: {}",
pageable.getPageNumber(), pageable.getPageSize(), userId);
// logger.info("查询课程任务 - 页码: {}, 每页数量: {}, 用户ID: {}",
// pageable.getPageNumber(), pageable.getPageSize(), userId);
Page<LessonTask> result;
if (userId != null) {
@ -46,16 +46,16 @@ public class LessonTaskService {
result = lessonTaskRepository.findAll(pageable);
}
logger.info("查询到 {} 条课程任务", result.getTotalElements());
// logger.info("查询到 {} 条课程任务", result.getTotalElements());
return result;
}
@Cacheable(value = "lessonTask", key = "#id")
public LessonTask findById(Long id) {
logger.info("根据ID查询课程任务 - 任务ID: {}", id);
// logger.info("根据ID查询课程任务 - 任务ID: {}", id);
return lessonTaskRepository.findById(id)
.orElseThrow(() -> {
logger.error("未找到ID为 {} 的课程任务", id);
// logger.error("未找到ID为 {} 的课程任务", id);
return new EntityNotFoundException("未找到ID为 " + id + " 的任务");
});
}
@ -63,21 +63,21 @@ public class LessonTaskService {
@Transactional
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
public LessonTask create(LessonTaskRequest request) {
logger.info("开始创建课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
request.getCourseName(), request.getMicroLessonName(), request.getUserId());
// logger.info("开始创建课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
// request.getCourseName(), request.getMicroLessonName(), request.getUserId());
validateRequest(request);
LessonTask task = new LessonTask();
BeanUtils.copyProperties(request, task);
task.setProgressStatus(0); // 初始状态未开始
LessonTask savedTask = lessonTaskRepository.save(task);
logger.info("创建课程任务成功 - 任务ID: {}", savedTask.getId());
// logger.info("创建课程任务成功 - 任务ID: {}", savedTask.getId());
return savedTask;
}
@Transactional
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
public LessonTask update(Long id, LessonTaskRequest request) {
logger.info("开始更新课程任务 - 任务ID: {}, 进度状态: {}", id, request.getProgressStatus());
// logger.info("开始更新课程任务 - 任务ID: {}, 进度状态: {}", id, request.getProgressStatus());
LessonTask task = findById(id);
// 只更新非空字段
@ -141,20 +141,20 @@ public class LessonTaskService {
task.setUpdatedAt(System.currentTimeMillis() / 1000);
LessonTask updatedTask = lessonTaskRepository.save(task);
logger.info("更新课程任务成功 - 任务ID: {}", updatedTask.getId());
// logger.info("更新课程任务成功 - 任务ID: {}", updatedTask.getId());
return updatedTask;
}
@Transactional
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
public void delete(Long id) {
logger.info("开始删除课程任务 - 任务ID: {}", id);
// logger.info("开始删除课程任务 - 任务ID: {}", id);
if (!lessonTaskRepository.existsById(id)) {
logger.error("未找到ID为 {} 的课程任务", id);
// logger.error("未找到ID为 {} 的课程任务", id);
throw new EntityNotFoundException("未找到ID为 " + id + " 的任务");
}
lessonTaskRepository.deleteById(id);
logger.info("删除课程任务成功 - 任务ID: {}", id);
// logger.info("删除课程任务成功 - 任务ID: {}", id);
}
/**
@ -165,7 +165,7 @@ public class LessonTaskService {
* @return 课程任务分页数据
*/
public Page<LessonTaskDTO> findByDepartmentIdAndNormalUser(Long departmentId, Pageable pageable) {
logger.info("查询部门正常用户的课程任务部门ID: {}", departmentId);
// logger.info("查询部门正常用户的课程任务部门ID: {}", departmentId);
Page<java.util.Map<String, Object>> result = lessonTaskRepository
.findByDepartmentIdAndNormalUserWithUsername(departmentId, pageable);
@ -185,7 +185,7 @@ public class LessonTaskService {
* @return 课程任务分页数据
*/
public Page<LessonTask> findByDepartmentIdAndStatus(Long departmentId, Integer status, Pageable pageable) {
logger.info("查询部门课程任务部门ID: {}, 状态: {}", departmentId, status);
// logger.info("查询部门课程任务部门ID: {}, 状态: {}", departmentId, status);
return lessonTaskRepository.findByDepartmentIdAndStatus(departmentId, status, pageable);
}
@ -198,7 +198,7 @@ public class LessonTaskService {
* @return 课程任务分页数据
*/
public Page<LessonTask> findByDepartmentIdAndUserStatus(Long departmentId, Integer userStatus, Pageable pageable) {
logger.info("查询部门课程任务部门ID: {}, 用户状态: {}", departmentId, userStatus);
// logger.info("查询部门课程任务部门ID: {}, 用户状态: {}", departmentId, userStatus);
return lessonTaskRepository.findByDepartmentIdAndUserStatus(departmentId, userStatus, pageable);
}

View File

@ -88,15 +88,15 @@ public class UserService implements UserDetailsService {
public ApiResponse<User> getCurrentUser(String token) {
String email = jwtService.extractUsername(token);
logger.info("从token中提取的邮箱: {}", email);
// logger.info("从token中提取的邮箱: {}", email);
Optional<User> userOpt = userRepository.findByEmail(email);
if (userOpt.isEmpty()) {
logger.warn("用户不存在: {}", email);
// logger.warn("用户不存在: {}", email);
return new ApiResponse<>(ErrorCode.USER_NOT_FOUND, "用户不存在", null);
}
User user = userOpt.get();
logger.info("找到用户: {}", user.getUsername());
// logger.info("找到用户: {}", user.getUsername());
user.setPassword(null);
return ApiResponse.success(user);
}
@ -172,7 +172,7 @@ public class UserService implements UserDetailsService {
}
public List<User> findByDepartmentId(Long departmentId) {
logger.info("查询部门用户列表部门ID: {}", departmentId);
// logger.info("查询部门用户列表部门ID: {}", departmentId);
return userRepository.findByDepartmentIdAndNormalStatus(departmentId);
}
@ -222,7 +222,7 @@ public class UserService implements UserDetailsService {
// 查找部门ID
Department department = departmentRepository.findByName(dto.getDepartmentName());
logger.info("查找部门:{},结果:{}", dto.getDepartmentName(), department);
// logger.info("查找部门:{},结果:{}", dto.getDepartmentName(), department);
if (department == null) {
errorMsg.append(String.format("第%d行部门不存在;", i + 2));
continue;
@ -242,12 +242,12 @@ public class UserService implements UserDetailsService {
user.setRoles(Integer.parseInt(roleAndJob));
user.setJobs(Integer.parseInt(roleAndJob));
} catch (NumberFormatException e) {
logger.warn("角色/岗位不是有效的数字: {}", roleAndJob);
// logger.warn("角色/岗位不是有效的数字: {}", roleAndJob);
errorMsg.append(String.format("第%d行角色/岗位不是有效的数字;", i + 2));
continue;
}
} else {
logger.warn("角色/岗位不能为空");
// logger.warn("角色/岗位不能为空");
errorMsg.append(String.format("第%d行角色/岗位不能为空;", i + 2));
continue;
}
@ -265,11 +265,11 @@ public class UserService implements UserDetailsService {
userRepository.save(user);
successCount++;
} catch (Exception e) {
logger.error("保存用户失败", e);
// logger.error("保存用户失败", e);
errorMsg.append(String.format("第%d行保存失败: %s;", i + 2, e.getMessage()));
}
} catch (Exception e) {
logger.error("导入第{}行数据失败", i + 2, e);
// logger.error("导入第{}行数据失败", i + 2, e);
errorMsg.append(String.format("第%d行导入失败;", i + 2));
}
}

View File

@ -29,16 +29,16 @@ public class JwtUtil {
private long jwtExpiration;
public String extractUsername(String token) {
logger.debug("开始从token中提取用户名");
// logger.debug("开始从token中提取用户名");
try {
String username = extractClaim(token, Claims::getSubject);
logger.debug("提取的用户名: {}", username);
// logger.debug("提取的用户名: {}", username);
return username;
} catch (ExpiredJwtException e) {
logger.error("token已过期", e);
// logger.error("token已过期", e);
throw e;
} catch (Exception e) {
logger.error("从token中提取用户名时发生错误", e);
// logger.error("从token中提取用户名时发生错误", e);
throw e;
}
}
@ -53,7 +53,7 @@ public class JwtUtil {
}
private Claims extractAllClaims(String token) {
logger.debug("开始从token中提取所有声明");
// logger.debug("开始从token中提取所有声明");
try {
Claims claims = Jwts
.parserBuilder()
@ -61,10 +61,10 @@ public class JwtUtil {
.build()
.parseClaimsJws(token)
.getBody();
logger.debug("声明提取成功");
// logger.debug("声明提取成功");
return claims;
} catch (Exception e) {
logger.error("从token中提取声明时发生错误", e);
// logger.error("从token中提取声明时发生错误", e);
throw e;
}
}
@ -73,16 +73,16 @@ public class JwtUtil {
try {
Date expiration = extractExpiration(token);
boolean isExpired = expiration.before(new Date());
logger.debug("token过期检查 - 过期时间: {}, 是否过期: {}", expiration, isExpired);
// logger.debug("token过期检查 - 过期时间: {}, 是否过期: {}", expiration, isExpired);
return isExpired;
} catch (Exception e) {
logger.error("检查token过期时发生错误", e);
// logger.error("检查token过期时发生错误", e);
throw e;
}
}
public String generateToken(String userName) {
logger.debug("开始为用户创建token: {}", userName);
// logger.debug("开始为用户创建token: {}", userName);
try {
Map<String, Object> claims = new HashMap<>();
String token = Jwts.builder()
@ -92,24 +92,24 @@ public class JwtUtil {
.setExpiration(new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000))
.signWith(getSignKey(), SignatureAlgorithm.HS384)
.compact();
logger.debug("token创建成功");
// logger.debug("token创建成功");
return token;
} catch (Exception e) {
logger.error("创建token时发生错误", e);
// logger.error("创建token时发生错误", e);
throw e;
}
}
public Boolean validateToken(String token, User user) {
logger.debug("开始验证用户token: {}", user.getUsername());
// logger.debug("开始验证用户token: {}", user.getUsername());
try {
final String username = extractUsername(token);
boolean isValid = username.equals(user.getUsername()) && !isTokenExpired(token);
logger.debug("token验证结果 - 用户名匹配: {}, 未过期: {}",
username.equals(user.getUsername()), !isTokenExpired(token));
// logger.debug("token验证结果 - 用户名匹配: {}, 未过期: {}",
// username.equals(user.getUsername()), !isTokenExpired(token));
return isValid;
} catch (Exception e) {
logger.error("验证token时发生错误", e);
// logger.error("验证token时发生错误", e);
return false;
}
}

View File

@ -1,7 +1,7 @@
# 数据库配置
spring.datasource.url=jdbc:mysql://172.16.215.132:3306/fenshenzhike?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://8.137.89.177:3306/jinduguanli?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=jinduguanli
spring.datasource.password=root041218
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=1218

View File

@ -5,9 +5,9 @@ spring:
main:
banner-mode: console
datasource:
url: jdbc:mysql://172.16.215.132:3306/fenshenzhike?useSSL=false&serverTimezone=UTC
username: root
password: 123
url: jdbc:mysql://8.137.89.177:3306/jinduguanli?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: jinduguanli
password: root041218
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
@ -18,7 +18,7 @@ spring:
format_sql: true
use_sql_comments: true
redis:
host: 172.16.215.132
host: 8.137.89.177
port: 6379
database: 0
timeout: 10000
@ -37,7 +37,7 @@ spring:
jwt:
secret: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
expiration: 86400000 # 24小时
expiration: 2592000000 # 24小时
logging:
level: