查看页面原型,明确需求需求
页面原型
需求分析
阅读接口文档
接口文档链接如下:
https://onedrive.live.com/?cid=C62793E731F0C1BE&id=C62793E731F0C1BE%2148
思路分析
用户发送请求,交由对应的Controller类进行处理,Controller类调用service实现查询部门功能,对应的service业务层调用对应的mapper接口,通过mapper接口查询数据库执行select * from dept;SQL语句,将查询结果返回给service,service将查询结果返回给Controller类,Controller将查询结果封装在统一查询结果Result类中,最终响应给前端。
功能接口的开发
控制层(Controller)
具体代码如下
package com.example.tlias.controller;import com.example.tlias.pojo.Dept;
import com.example.tlias.pojo.Result;
import com.example.tlias.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.logging.Logger;@RestController
@Slf4j // 日志注解
public class DeptController {@Autowired// 注入service对象private DeptService deptService;// 获取日志记录对象// todo 查询部门信息// 指定请求路径及方式// @RequestMapping(value = "/depts", method = RequestMethod.GET)// 上述注解的简化@GetMapping("depts")public Result list() {log.info("查询全部部门数据");// 调用service查询部门信息List<Dept> deptList = deptService.list();return Result.success(deptList);}
}
业务层(Service)
具体代码如下
Service接口
package com.example.tlias.service;import com.example.tlias.pojo.Dept;import java.util.List;public interface DeptService {/*** 查询全部部门数据** @return*/List<Dept> list();
}
Service接口实现类
package com.example.tlias.service.impl;import com.example.tlias.mapper.DeptMapper;
import com.example.tlias.pojo.Dept;
import com.example.tlias.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class DeptServiceImpl implements DeptService {@Autowiredprivate DeptMapper deptMapper;@Overridepublic List<Dept> list() {return deptMapper.list();}
}
持久层(Mapper)
package com.example.tlias.mapper;import com.example.tlias.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper
public interface DeptMapper {/*** 查询全部的部门数据** @return*/@Select("select * from dept")List<Dept> list();
}
接口测试
使用Postman来进行接口测试,首先启动SpringBoot项目,然后再在Postman中发送对应请求
具体运行结果如下
{"code": 1,"msg": "success","data": [{"id": 1,"name": "学工部","createTime": "2023-08-07T15:44:50","updateTime": "2023-08-07T15:44:50"},{"id": 2,"name": "教研部","createTime": "2023-08-07T15:44:50","updateTime": "2023-08-07T15:44:50"},{"id": 3,"name": "咨询部","createTime": "2023-08-07T15:44:50","updateTime": "2023-08-07T15:44:50"},{"id": 4,"name": "就业部","createTime": "2023-08-07T15:44:50","updateTime": "2023-08-07T15:44:50"},{"id": 5,"name": "人事部","createTime": "2023-08-07T15:44:50","updateTime": "2023-08-07T15:44:50"}]
}
由于在控制类中使用的注解为@RestController(@Controller`和`@ResponseBody`注解的组合),控制类会自动将返回给前端的结果转换为JSON格式的数据。测试成功