day03--web实战(部门管理)

27 阅读2分钟

1. 开发规范与工具

  • 前后端分离:前端/后端独立开发,通过接口文档约定 URL、参数、返回格式(统一用 Result 包装)。

  • RESTful 风格

    • URL 定位资源(用复数:/depts)--代表某一类资源
    • HTTP 方法表示动作:GET/POST/PUT/DELETE
  • 接口调试工具:用 Apifox 做接口调试、Mock、测试(浏览器只能方便发 GET,不适合全量测试)。


2. 工程搭建(部门模块基础骨架)

  • 建表:dept(id, name, create_time, update_time)

  • 配置:application.yml 配置数据源 + MyBatis 日志

  • 代码结构三层:

    • controller:接收请求 + 返回 Result
    • service:业务逻辑(补时间、调用 mapper)
    • mapper:SQL(MyBatis)
  • 实体类:Dept(id, name, createTime, updateTime)

  • 统一返回:Result.success(data) / Result.error(msg)


3. 部门 CRUD 接口(核心)

3.1 查询全部

  • GET /depts
  • Controller 调 Service → Mapper select * from dept
  • 请求方式限制:用 @GetMapping(比 @RequestMapping(method=...)更简洁)

3.2 删除

  • DELETE /depts?id=1

  • 简单参数接收(推荐):形参同名直接收 Integer id

    • 也可 @RequestParam / HttpServletRequest(不推荐)

3.3 新增

  • POST /depts,Body:{"name":"研发部"}

  • JSON 参数接收@RequestBody Dept dept

  • Service 层补全:

    • createTime = now
    • updateTime = now
  • Mapper:insert into dept(...) values(#{name},#{createTime},#{updateTime})

3.4 修改(两步)

  1. 查询回显
  • GET /depts/{id}
  • 路径参数@PathVariable Integer id
  1. 修改提交
  • PUT /depts,Body:{"id":1,"name":"研发部"}
  • Service 补全:updateTime = now
  • Mapper:update dept set name=?, update_time=? where id=?

3.5 路径抽取

  • 类上加:@RequestMapping("/depts")
  • 方法上写:@GetMapping / @PostMapping / @PutMapping / @DeleteMapping(路径更短更清爽)

4. MyBatis 字段映射坑

  • 数据库:create_time / update_time

  • Java:createTime / updateTime

  • 解决方案三选一:

    1. @Results 手动映射

    2. SQL 起别名 create_time createTime

    3. 开启驼峰映射(推荐)

      mybatis:
        configuration:
          map-underscore-to-camel-case: true
      

5. 前后端联调与 Nginx 反向代理

  • 前端通过 Nginx 访问:http://localhost:90/api/depts
  • Nginx 反向代理转发到后端 Tomcat(隐藏后端、灵活扩缩、可做负载均衡)
  • 典型流程:location /api → rewrite → proxy_pass 到后端服务

6. 日志(替代 System.out)

  • 为什么不用 println:硬编码、不可控、只能控制台、不利维护

  • 常用体系:SLF4J 门面 + Logback 实现

  • SpringBoot 默认带 Logback(通常不用额外引依赖)

  • 用法(推荐):

    • 类上加 @Slf4j

    • 记录关键业务日志:

      • 查询/新增/删除/修改
      • 带参数:log.info("删除部门 id: {}", id);
  • logback.xml 可配:输出格式、控制台/文件、级别(info/debug等)