开发规范-Restful风格介绍

开发规范-统一响应结果介绍

案例-部门管理-查询-思路

三层架构代码:
Controller层:DeptController(部门管理Controller层,接收请求,调用service查询部门数据,因此自动注入DeptService ,最后给出响应结果)
package com.itheima.controller;import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
@Slf4j
@RestController
public class DeptController {@Autowiredprivate DeptService deptService;@GetMapping("/depts")public Result list(){List<Dept> deptList = deptService.list();log.info("部门查询记录");return Result.success(deptList);}
}
Service层 :DeptService(部门管理Service的接口),DeptServiceImpl(实现部门管理Service的接口-调用mapper接口查询,因此自动注入DeptMapper)
DeptService
package com.itheima.service;import com.itheima.pojo.Dept;import java.util.List;
public interface DeptService {List<Dept> list();
}
DeptServiceImpl
package com.itheima.service.impl;import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.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层 :DeptMapper(接口,执行SQL语句查询部门信息并把结果以集合类型(泛型为部门类)返回)
package com.itheima.mapper;import com.itheima.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;
@Mapper
public interface DeptMapper {@Select("select * from dept")List<Dept> list();
}
其他代码:
案例目录结构

pojo(存放各种实体类)
Dept(部门实体类)
package com.itheima.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Dept {private Integer id; private String name; private LocalDateTime createTime; private LocalDateTime updateTime;
}
Result(响应实体类)
package com.itheima.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {private Integer code;private String msg; private Object data; public static Result success(){return new Result(1,"success",null);}public static Result success(Object data){return new Result(1,"success",data);}public static Result error(String msg){return new Result(0,msg,null);}
}
前后端联调结果(前端直接使用部署在Nginx的前端工程)
