代碼開發
package com.sky.controller.admin;import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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("/admin/employee")
@Slf4j
@Api(tags = "員工相關接口")
public class EmployeeController {@Autowiredprivate EmployeeService employeeService;@Autowiredprivate JwtProperties jwtProperties;/*** 新增員工* @param employeeDTO* @return*/@PostMapping@ApiOperation("新增員工")public Result save(@RequestBody EmployeeDTO employeeDTO){log.info("新增員工{}", employeeDTO);employeeService.save(employeeDTO);return Result.success();}
}
package com.sky.service;import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;public interface EmployeeService {/*** 新增員工* @param employeeDTO*/void save(EmployeeDTO employeeDTO);
}
package com.sky.service.impl;import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;import java.time.LocalDateTime;@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {@Autowiredprivate EmployeeMapper employeeMapper;/*** 新增員工* @param employeeDTO*/@Overridepublic void save(EmployeeDTO employeeDTO) {Employee employee = new Employee();// 對象屬性拷貝BeanUtils.copyProperties(employeeDTO,employee);// 設置賬號狀態,默認正常狀態,1表示正常0表示禁用employee.setStatus(StatusConstant.ENABLE);// 設置密碼,默認密碼123456employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));// 設置創建時間和修改時間employee.setCreateTime(LocalDateTime.now());employee.setUpdateTime(LocalDateTime.now());// 設置創建人id和修改人id
// TODO 后期需要修改為當前登錄用戶的idemployee.setCreateUser(10L);employee.setUpdateUser(10L);employeeMapper.insert(employee);}}
package com.sky.mapper;import com.sky.entity.Employee;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;@Mapper
public interface EmployeeMapper {/*** 插入員工數據* @param employee*/@Insert("insert into employee (name, username, password, phone, sex, id_number, status,"+"create_time, update_time, create_user, update_user) "+"values (#{name},#{username},#{password},#{phone},#{sex},#{idNumber},#{status},"+"#{createTime},#{updateTime},#{createUser},#{updateUser})")void insert(Employee employee);
}
功能測試
開發階段,后端測試主要以接口文檔測試為主。
先獲得登錄令牌:
通過接口文檔測試
通過前后端聯調測試
代碼完善
程序存在問題
1、錄入的用戶名已存在,拋出異常后沒有處理
2、新增員工時,創建人id和修改人id設置為了固定值
處理
拋出異常
1、先發現異常:把已存在的用戶名,在重新發送。
? ? ? ? idea顯示錯誤
java.sql.SQLIntegrityConstraintViolationException:
Duplicate entry 'zhangsan' for key 'idx_username'
2、在全局異常處理器中添加該異常
package com.sky.handler;import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.sql.SQLIntegrityConstraintViolationException;/*** 全局異常處理器,處理項目中拋出的業務異常*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {/*** 捕獲業務異常* @param ex* @return*/@ExceptionHandlerpublic Result exceptionHandler(BaseException ex){log.error("異常信息:{}", ex.getMessage());return Result.error(ex.getMessage());}/*** 處理sql重復存在名異常*/@ExceptionHandlerpublic Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
// Duplicate entry 'zhangsan' for key 'idx_username'String message = ex.getMessage();if(message.contains("Duplicate entry")){String[] split = message.split(" ");
// 獲取用戶名String username = split[2];
// String msg = username + "已存在";String msg = username + MessageConstant.ALREDY_EXISTS;return Result.error(msg);}else {
// 未知錯誤return Result.error(MessageConstant.UNKNOWN_ERROR);}}}
設置創建人id和修改人id
ThreadLocal 并不是一個Thread,而是Thread的局部變量。 ThreadLocal為每個線程提供單獨一份存儲空間,具有線程隔離的效果,只有在線程內才能獲取到對應的值,線程外則不能訪問。
ThreadLocal常用方法:
public void set(T value) ?? ?設置當前線程的線程局部變量的值
public T get() ?? ??? ?返回當前線程所對應的線程局部變量的值
public void remove() ? ? ? ?移除當前線程的線程局部變量
package com.sky.context;public class BaseContext {public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();public static void setCurrentId(Long id) {threadLocal.set(id);}public static Long getCurrentId() {return threadLocal.get();}public static void removeCurrentId() {threadLocal.remove();}}
employee.setCreateUser(BaseContext.getCurrentId());employee.setUpdateUser(BaseContext.getCurrentId());