目标: 将原本的控制器, 拆分成三层:
- 1.控制器(接受请求和响应)
- 2.service层(业务逻辑)
- 3.dao层(数据获取)


步骤
- 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() {
List<Emp> empList = empDao.listEmp();
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();
}
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() {
String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
System.out.println(file);
List<Emp> empList = XmlParserUtils.parse(file, Emp.class);
return empList;
}
}
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()
{
List<Emp> empList = empService.listEmp();
return Result.success(empList);
}
}