611 字
3 分钟
部门修改功能
AI 摘要
部门修改功能
定义
部门修改功能分为两个步骤:查询回显和修改数据。查询回显根据 ID 获取部门数据用于页面展示,修改数据接收 JSON 请求体更新数据库记录。涉及路径参数接收(@PathVariable)和 @RequestMapping 路径抽取。
查询回显
接口描述
- 请求方式:GET
- 请求路径:
/depts/{id} - 请求参数:路径参数
id - 响应数据:
Result(data 为 Dept 对象)
实现思路

路径参数接收
/depts/1、/depts/2 这种在 URL 中传递的参数称为路径参数。使用 @PathVariable 注解获取:

路径参数名与 Controller 方法形参名称一致时,@PathVariable 的 value 属性可省略。
代码实现
// Controller@GetMapping("/depts/{id}")public Result getById(@PathVariable Integer id) { System.out.println("根据ID查询, id=" + id); Dept dept = deptService.getById(id); return Result.success(dept);}
// ServiceDept getById(Integer id);
// ServiceImplpublic Dept getById(Integer id) { return deptMapper.getById(id);}
// Mapper@Select("select id, name, create_time, update_time from dept where id = #{id}")Dept getById(Integer id);修改数据
接口描述
- 请求方式:PUT
- 请求路径:
/depts - 请求参数:JSON 格式
{"id":1, "name":"研发部"} - 响应数据:
Result
实现思路

代码实现
// Controller@PutMapping("/depts")public Result update(@RequestBody Dept dept) { System.out.println("修改部门, dept=" + dept); deptService.update(dept); return Result.success();}
// Servicevoid update(Dept dept);
// ServiceImplpublic void update(Dept dept) { dept.setUpdateTime(LocalDateTime.now()); // 补全更新时间 deptMapper.update(dept);}
// Mapper@Update("update dept set name = #{name}, update_time = #{updateTime} where id = #{id}")void update(Dept dept);@RequestMapping 路径抽取
部门相关接口请求路径都以 /depts 开头。可将公共路径抽取到类上:
@Slf4j@RequestMapping("/depts")@RestControllerpublic class DeptController {
@GetMapping // → /depts (GET) public Result list() { ... }
@DeleteMapping // → /depts (DELETE) public Result delete(Integer id) { ... }
@PostMapping // → /depts (POST) public Result save(@RequestBody Dept dept) { ... }
@GetMapping("/{id}") // → /depts/{id} (GET) public Result getById(@PathVariable Integer id) { ... }
@PutMapping // → /depts (PUT) public Result update(@RequestBody Dept dept) { ... }}完整请求路径 = 类上的 @RequestMapping 的 value + 方法上的映射注解的 value。
常见场景
- 编辑表单的”回显-修改-保存”两阶段交互
- RESTful 风格中 PUT + 路径参数的组合使用
- 同类接口的公共路径抽取,减少重复代码
注意事项
- 路径参数名与形参名一致时可省略
@PathVariable的 value @RequestBody用于接收 JSON 请求体,@PathVariable用于接收 URL 路径参数- 修改操作每次都应更新
updateTime字段 - 抽取公共路径到类上后,方法上的路径只需写差异部分
支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!
最后更新于 2026-05-21,距今已过 30 天
部分内容可能已过时
评论区
[ 标签 ]
[ 分类 ]
[ 公告 ]
如果你喜欢,那么欢迎来到我的世界!
了解更多[ 音乐 ]
找不到相关结果。
[ contents ]
[ 全部文章 ]