Authentication对象实现个人心中功能模块

紧接着上一篇,这一篇实现员工工资账套和个人中心模块

目录

  • 1.工资账套管理
    • 1.1实现功能
    • 1.2.员工账套管理
    • 1.3.测试功能
  • 2.个人中心
    • 2.1.个人中心操作

1.工资账套管理

单表增删改查,需要注意的就是对应实体类表需要修改日期格式。

1.1实现功能

修改日期格式:

Salary.java

@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_salary")
@ApiModel(value="Salary对象", description="")
public class Salary implements Serializable {

    ......

    @ApiModelProperty(value = "启用时间")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "Asia/Shanghai")
    private LocalDateTime createDate;

    ......

}

SalaryController.java

@RestController
@RequestMapping("/salary/sob")
public class SalaryController {

    @Resource
    private ISalaryService salaryService;

    @ApiOperation(value = "获取所有工资账套")
    @GetMapping("/")
    public List<Salary> getAllSalaries() {
        return salaryService.list();
    }

    @ApiOperation(value = "添加工资账套")
    @PostMapping("/")
    public RespBean addSalary(@RequestBody Salary salary) {
        salary.setCreateDate(LocalDateTime.now());
        if (salaryService.save(salary)) {
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "删除工资账套")
    @DeleteMapping("/{id}")
    public RespBean deleteSalary(@PathVariable Integer id) {
        if (salaryService.removeById(id)) {
            return RespBean.success("删除成功!");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "更新工资账套")
    @PutMapping("/")
    public RespBean updateSalary(@RequestBody Salary salary) {
        if (salaryService.updateById(salary)) {
            return RespBean.success("更新成功!");
        }
        return RespBean.success("更新失败!");
    }
}

1.2.员工账套管理

每个员工的账套,员工表中有个salaryId属性,对应Salary表中的模板。

1.2.1.Mapper接口

EmployeeMapper.java

public interface EmployeeMapper extends BaseMapper<Employee> {
    
    ......

    /**
     * 获取所有员工账套
     * @param page
     * @return
     */
    IPage<Employee> getEmpWithSalary(Page<Employee> page);
}

1.2.2.映射文件

EmployeeMapper.xml

<resultMap id="EmployeeWithSalary" type="com.kt.pojo.Employee" extends="BaseResultMap">
        <association property="salary" javaType="com.kt.pojo.Salary">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="sbonus" property="bonus"/>
            <result column="sbasicSalary" property="basicSalary"/>
            <result column="slunchSalary" property="lunchSalary"/>
            <result column="strafficSalary" property="trafficSalary"/>
            <result column="sallSalary" property="allSalary"/>
            <result column="spensionBase" property="pensionBase"/>
            <result column="spensionPer" property="pensionPer"/>
            <result column="smedicalBase" property="medicalBase"/>
            <result column="smedicalPer" property="medicalPer"/>
            <result column="saccumulationFundBase" property="accumulationFundBase"/>
            <result column="saccumulationFundPer" property="accumulationFundPer"/>
        association>
        <association property="department" javaType="com.kt.pojo.Department">
            <result column="dname" property="name"/>
        association>
    resultMap>


<select id="getEmpWithSalary" resultMap="EmployeeWithSalary">
    SELECT
        e.*,
        d.`name` AS dname,
        s.id AS sid,
        s.`name` AS sname,
        s.basicSalary AS sbasicSalary,
        s.lunchSalary AS slunchSalary,
        s.bonus AS sbonus,
        s.trafficSalary AS strafficSalary,
        s.allSalary AS sallSalary,
        s.pensionBase AS spensionBase,
        s.pensionPer AS spensionPer,
        s.medicalPer AS smedicalPer,
        s.medicalBase AS smedicalBase,
        s.accumulationFundPer AS saccumulationFundPer,
        s.accumulationFundBase AS saccumulationFundBase
    FROM
     t_employee e
 LEFT JOIN t_salary s ON e.salaryId = s.id
 LEFT JOIN t_department d ON e.departmentId = d.id
    ORDER BY
     e.id
select>

1.2.3.服务类

IEmployeeService.java

public interface IEmployeeService extends IService<Employee> {

	......

    /**
     * 获取所有员工账套
     * @param currentPage
     * @param size
     * @return
     */
    RespPageBean getEmpWithSalary(Integer currentPage, Integer size);
}

1.2.4.服务实现类

EmployeeServiceImpl.java

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
   
  	 ......

    @Override
    public RespPageBean getEmpWithSalary(Integer currentPage, Integer size) {
        // 开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> employeeIPage = employeeMapper.getEmpWithSalary(page);
        RespPageBean pageBean = new RespPageBean(employeeIPage.getTotal(), employeeIPage.getRecords());
        return pageBean;
    }
}

1.2.5.员工账套控制类

SalarySobCfgController.java

@RestController
@RequestMapping("/salary/sobcfg")
public class SalarySobCfgController {

    @Resource
    private ISalaryService salaryService;
    @Resource
    private IEmployeeService employeeService;

    @ApiOperation(value = "获取所有工资账套")
    @GetMapping("/salaries")
    public List<Salary> getAllSalaries() {
        return salaryService.list();
    }

    @ApiOperation(value = "获取所有员工账套")
    @GetMapping("/")
    public RespPageBean getEmpWithSalary(@RequestParam(defaultValue = "1") Integer currentPage,
                                         @RequestParam(defaultValue = "10") Integer size) {
        return employeeService.getEmpWithSalary(currentPage, size);
    }

    @ApiOperation(value = "更新员工账套")
    @PutMapping("/")
    public RespBean updateEmpSalary(Integer eid, Integer sid) {
        if (employeeService.update(new UpdateWrapper<Employee>().set("salaryId", sid).eq("id", eid))) {
            return RespBean.success("更新成功!");
        }
        return RespBean.error("更新失败!");
    }
}

1.3.测试功能

获取所有员工账套:

Authentication对象实现个人心中功能模块_第1张图片

获取所有工资账套:

Authentication对象实现个人心中功能模块_第2张图片

2.个人中心

在普通项目中需要获取当前登录用户的信息,一般做法是在登录成功后,将当前用户信息存入 session中,在需要的时候从session里面读取,更新用户信息也是直接通过数据库进行相应的更新。

在Spring Security中要如何获取用户信息和更新用户信息呢?

在Spring Security中提供了一个Authentication对象,我们可以在Controller或者Service中,直接注入Authentication,注入成功后,就能直接使用。这样我们就能通过Authentication对象直接获取用户信息。

在Spring Security中更新用户信息,出了正常的去数据库进行相应的更新之外,还需要重新构建Authentication对象,这样才能在项目中正确的获取到更新后的用户信息。具体代码如下:

2.1.个人中心操作

2.1.1.服务类

IAdminService.java

public interface IAdminService extends IService<Admin> {

  	......

    /**
     * 更新用户密码
     * @param oldPwd
     * @param pwd
     * @param adminId
     * @return
     */
    RespBean updateAdminPwd(String oldPwd, String pwd, Integer adminId);
}

2.1.2.服务实现类

AdminServiceImpl.java

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

	......
        
    @Override
    public RespBean updateAdminPwd(String oldPwd, String pwd, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 判断旧密码是否正确
        if (encoder.matches(oldPwd, admin.getPassword())) {
            admin.setPassword(encoder.encode(pwd));
            int result = adminMapper.updateById(admin);
            if (1 == result) {
                return null;
            }
        }
        return RespBean.error("更新失败");
    }
}

2.1.3.自定义Authority解析器

CustomAuthorityDeserializer.java

public class CustomAuthorityDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode jsonNode = mapper.readTree(jsonParser);
        List<GrantedAuthority> grantedAuthorities = new LinkedList<>();
        Iterator<JsonNode> elements = jsonNode.elements();
        while (elements.hasNext()) {
            JsonNode next = elements.next();
            JsonNode authority = next.get("authority");
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
        }
        return grantedAuthorities;
    }
}

2.1.4.修改实体类

Admin.java

@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_admin")
@ApiModel(value="Admin对象", description="")
public class Admin implements Serializable , UserDetails {

	......
        
    @ApiModelProperty(value = "角色/权限")
    @TableField(exist = false)
    private List<Role> roles;

    @Override
    @JsonDeserialize(using = CustomAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorityList = roles
                .stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());
        return authorityList;
    }

	......
}

到这里基本功能就大致实现完了,有许多测试我们等到了前端弄好之后进行前端界面化测试,这样更加直观个清楚。有许多模块的功能还没写,后期还会补齐这些功能,以及优化部分功能。

你可能感兴趣的:(Java,项目练习,java,spring,boot,后端,mysql)