【java】【项目实战】[外卖三]登录优化与员工管理业务开发

前言:无权限访问系统成功,需要完善登录功能;实现员工管理页面开发

一、完善登录功能

1.1 问题分析

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第1张图片

1.2 代码实现

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第2张图片1.2.1 自定义过滤器LoginCheckFilter

 

package com.runa.reggie.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到请求:{}",request.getRequestURL());

        

        filterChain.doFilter(request,response);
    }
}

1.2.2 启动类ReggieApplication加入注解@ServletComponentScan

package com.runa.reggie;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@Slf4j
@SpringBootApplication
@ServletComponentScan
public class ReggieApplication {
    public static void main(String[] args) {
        SpringApplication.run(ReggieApplication.class,args);
        log.info("项目启动成功~~~");
    }
}

1.2.3 完善 过滤器LoginCheckFilter处理逻辑

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第3张图片

 

package com.runa.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.runa.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1  获取本次请求的URI
        //        request.getRequestURL()返回的是全路径。
        //        request.getRequestURI()返回的是除去协议,域名(IP+端口号)之后的路由部分。
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:【{}】",requestURI);

        // 定义一些不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",    // 登录不需要
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };

        // 2  判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        // 3 如果不需要处理,则直接放行
        if(check){
            log.info("本次请求【 {} 】 不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        // 4 判断登录状态,如果已登录,则直接放行
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已登录,请求url为:【{}】, 用户id为:【 {} 】 ",requestURI,request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        // 5 如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配,检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        // 循环都匹配不上就返回false
        return false;
    }
}

1.3 功能测试

启动服务,不登录

访问:http://localhost:8080/backend/index.html

 

二、新增员工

2.1 需求分析

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第4张图片

 

2.2 数据模型

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第5张图片

 

2.3 代码开发

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第6张图片

 2.3.1 EmployeeController

package com.runa.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Employee;
import com.runa.reggie.service.impl.EmployeeServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
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 javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServcie employeeServcie;


    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    //HttpServletRequest request  是为了将登录对象塞入session
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeServcie.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对,如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        // 清理Session 中保存的当前员工的id
        request.getSession().removeAttribute("emplyee");

        return R.success("退出成功!");

    }

    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee){
        log.info("新增员工,员工信息为:{}",employee.toString());
        // 设置初始密码123456,需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeServcie.save(employee);
        return R.success("新增员工成功");
    }

}

2.4 功能测试

启动服务,添加员工

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第7张图片

2.5 唯一约束异常

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第8张图片

 2.5.1 全局异常处理GlobaExceptionHandler

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第9张图片

 

package com.runa.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})   // 加了RestController Controller 注解的
@ResponseBody
@Slf4j
public class GlobaExceptionHandler {
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String msg = ex.getMessage();
        log.info(msg);
        if(msg.contains("Duplicate entry")){
            String[] split = msg.split(" "); //空分割
            String resultMsg = split[2] + " 已存在 ";
            return R.error(resultMsg);

        }
        return R.error("未知错误!");
    }
}

三、员工信息分页查询

3.1 需求分析

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第10张图片

 

3.2 代码开发

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第11张图片

3.2.1 分页插件MybatisPlusConfig

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第12张图片

package com.runa.reggie.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置MP的分页插件
 */
@Configuration
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;

    }
}

 

3.2.2 EmployeeController

package com.runa.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Employee;
import com.runa.reggie.service.impl.EmployeeServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServcie employeeServcie;


    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    //HttpServletRequest request  是为了将登录对象塞入session
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeServcie.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对,如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        // 清理Session 中保存的当前员工的id
        request.getSession().removeAttribute("emplyee");

        return R.success("退出成功!");

    }

    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee){
        log.info("新增员工,员工信息为:{}",employee.toString());
        // 设置初始密码123456,需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeServcie.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize,String name){
        log.info("page= {}, pageSize= {}, name = {}",page, pageSize, name);

        // 构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper();
         // 添加过滤条件//当传入的name不为空的时候才会添加条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);



        //执行查询
        employeeServcie.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

}

3.3 功能测试

启动服务测试

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第13张图片

 

四、启用/禁用员工账号

4.1 需求分析

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第14张图片

 【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第15张图片

 

4.2 代码实现

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第16张图片

 【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第17张图片

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第18张图片 

 

4.2.2 EmployeeController

package com.runa.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Employee;
import com.runa.reggie.service.impl.EmployeeServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServcie employeeServcie;


    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    //HttpServletRequest request  是为了将登录对象塞入session
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeServcie.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对,如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        // 清理Session 中保存的当前员工的id
        request.getSession().removeAttribute("emplyee");

        return R.success("退出成功!");

    }

    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee){
        log.info("新增员工,员工信息为:{}",employee.toString());
        // 设置初始密码123456,需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeServcie.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize,String name){
        log.info("page= {}, pageSize= {}, name = {}",page, pageSize, name);

        // 构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper();
         // 添加过滤条件//当传入的name不为空的时候才会添加条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);



        //执行查询
        employeeServcie.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 根据ID修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpServletRequest request, @RequestBody Employee employee){
        log.info(employee.toString());

        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());

        employeeServcie.updateById(employee);

        return R.success("员工信息修改成功");

    }

}

4.3 功能测试

启动服务,开始测试

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第19张图片

 

4.4 代码修复

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第20张图片

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第21张图片 

 4.4.1 对象映射器类JacksonObjectMapper

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第22张图片

package com.runa.reggie.common;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

/**
 * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
 * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
 */
public class JacksonObjectMapper extends ObjectMapper {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    public JacksonObjectMapper() {
        super();
        //收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);

        //反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


        SimpleModule simpleModule = new SimpleModule()
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))

                .addSerializer(BigInteger.class, ToStringSerializer.instance)
                .addSerializer(Long.class, ToStringSerializer.instance)
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        //注册功能模块 例如,可以添加自定义序列化器和反序列化器
        this.registerModule(simpleModule);
    }
}

 4.4.2 WebMvcConfig

package com.runa.reggie.config;

import com.runa.reggie.common.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * 设置静态资源映射
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("~~~开始进行静态资源映射...~~");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }

    /**
     * 扩展MVC框架的消息转换器
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List> converters) {
        log.info("扩展消息转换器。。。。");
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,底层使用Jackson将java对象转为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到MVC框架转换器集合中
        converters.add(0,messageConverter);
    }
}

五、编辑员工信息

5.1 需求分析

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第23张图片

 

5.2 代码开发

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第24张图片

 

5.2.1 EmployeeController 实现回显GetById方法

package com.runa.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Employee;
import com.runa.reggie.service.impl.EmployeeServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServcie employeeServcie;


    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    //HttpServletRequest request  是为了将登录对象塞入session
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeServcie.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对,如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        // 清理Session 中保存的当前员工的id
        request.getSession().removeAttribute("emplyee");

        return R.success("退出成功!");

    }

    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee){
        log.info("新增员工,员工信息为:{}",employee.toString());
        // 设置初始密码123456,需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeServcie.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize,String name){
        log.info("page= {}, pageSize= {}, name = {}",page, pageSize, name);

        // 构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper();
         // 添加过滤条件//当传入的name不为空的时候才会添加条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);



        //执行查询
        employeeServcie.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 根据ID修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpServletRequest request, @RequestBody Employee employee){
        log.info(employee.toString());

        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());

        employeeServcie.updateById(employee);

        return R.success("员工信息修改成功");

    }

    @GetMapping("/{id}")
    public R GetById(@PathVariable Long id){
        log.info("根据id查询员工:{}",id);

        Employee employee = employeeServcie.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

}

保存方法与添加相同接口

5.3 功能测试

【java】【项目实战】[外卖三]登录优化与员工管理业务开发_第25张图片

 

你可能感兴趣的:(java,java,开发语言)