[Java2023] T5-三层架构改造员工列表

133 阅读1分钟

目标: 将原本的控制器, 拆分成三层:

  • 1.控制器(接受请求和响应)
  • 2.service层(业务逻辑)
  • 3.dao层(数据获取)

image.png

image.png

步骤

  • 1.创建src/main/java/com/itheima/service/EmpService.java 接口类和相应目录
package com.itheima.service;
import com.itheima.pojo.Emp;
import java.util.List;
public interface EmpService {
    public List<Emp> listEmp();
}
  • 2.创建 impl/EmpServiceA.java 实现上面的接口, 快捷键 ctrl+i
package com.itheima.service.impl;
import com.itheima.dao.EmpDao;
import com.itheima.dao.impl.EmpDaoA;
import com.itheima.pojo.Emp;
import com.itheima.service.EmpService;
import java.util.List;
public class EmpServiceA implements EmpService {
    private EmpDao empDao = new EmpDaoA();
    @Override
    public List<Emp> listEmp() {
        // 1.调用dao获取数据
        List<Emp> empList = empDao.listEmp();
        // 2.数据处理
        empList.stream().forEach(emp -> {
            String gender = emp.getGender();
            if ("1".equals(gender)) {
                emp.setGender("男");
            } else if ("2".equals(gender)) {
                emp.setGender("女");
            }
            String job = emp.getJob();
            if ("1".equals(gender)) {
                emp.setGender("讲师");
            } else if ("2".equals(gender)) {
                emp.setGender("班主任");
            } else if ("3".equals(gender)) {
                emp.setGender("就业指导");
            }
        });
        return empList;
    }
}
  • 3.创建src/main/java/com/itheima/dao/EmpDao.java 接口类和相应目录
package com.itheima.dao;
import com.itheima.pojo.Emp;
import java.util.List;
/**
 * 用于获取员工数据的接口类
 */
public interface EmpDao {
    public List<Emp> listEmp();
}
  • 4.创建impl/EmpDaoA.java
package com.itheima.dao.impl;
import com.itheima.dao.EmpDao;
import com.itheima.pojo.Emp;
import com.itheima.utils.XmlParserUtils;
import java.util.List;
public class EmpDaoA implements EmpDao {
    @Override
    public List<Emp> listEmp() {
        // 1.加载并解析xml
        String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
        System.out.println(file);
        List<Emp> empList = XmlParserUtils.parse(file, Emp.class);
        return empList;
    }
}
  • 5.最后修改控制器
package com.itheima.controller;
import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.service.impl.EmpServiceA;
import com.itheima.utils.XmlParserUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmpController {
    private EmpService empService = new EmpServiceA();
    @RequestMapping("listEmp")
    public Result list()
    {
        // 1.调用service, 获取数据
        List<Emp> empList = empService.listEmp();
        // 3.响应数据
        return Result.success(empList);
    }
}