SpringBoot Rest风格 API

一、添加Rest API

1.1 添加部门

java 复制代码
/**
* 添加部门 
*/
@Log
@PostMapping
public Result add(@RequestBody Dept dept){
    System.out.println("添加部门: " + dept);
    deptService.add(dept);
    return Result.success();
}

1.2 添加分类

java 复制代码
 @PutMapping
    @ApiOperation(value = "保存Category",notes = "添加Category")
    @ApiImplicitParam(name = "categoryVO",value = "保险分类VO对象",required = true,dataType = "CategoryVO")
    @ApiOperationSupport(includeParameters = {"categoryVO.dataState","categoryVO.parentCategoryNo",
            "categoryVO.categoryName","categoryVO.icon","categoryVO.leafNode","categoryVO.showIndex",
            "categoryVO.categoryType","categoryVO.sortNo","categoryVO.remake","categoryVO.insuranceType",
            "categoryVO.categoryClaimVOs.claimKey","categoryVO.categoryConditionVOs.conditionKey",
            "categoryVO.categoryCoefficentVOs.coefficentKey","categoryVO.categorySafeguardVOs.safeguardKey"})
    public ResponseResult<CategoryVO> createCategory(@RequestBody CategoryVO categoryVO) {
        CategoryVO categoryVOResult = categoryService.save(categoryVO);
        return ResponseResultBuild.successBuild(categoryVOResult);
    }

二、查询 Rest API

2.1查询部门

java 复制代码
/**
* 根据ID查询部门数据
* @return
*/
@GetMapping("/{id}")
public Result getInfo(@PathVariable Integer id){
    System.out.println("根据ID查询部门数据: " + id);
    return Result.success();
}
java 复制代码
@GetMapping("/depts/{id}/{status}")
public Result getInfo(@PathVariable Integer id, @PathVariable Integer sta){
	//...
}

2.2 查询分类

java 复制代码
  @PostMapping("page/{pageNum}/{pageSize}")
    @ApiOperation(value = "分类分页",notes = "分类分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryVO",value = "分类VO对象",required = true,dataType = "CategoryVO"),
            @ApiImplicitParam(paramType = "path",name = "pageNum",value = "页码",example = "1",dataType = "Integer"),
            @ApiImplicitParam(paramType = "path",name = "pageSize",value = "每页条数",example = "10",dataType = "Integer")
    })
    public ResponseResult<Page<CategoryVO>> findCategoryVOPage(
            @RequestBody CategoryVO categoryVO,
            @PathVariable("pageNum") int pageNum,
            @PathVariable("pageSize") int pageSize) {
        Page<CategoryVO> categoryVOPage = categoryService.findPage(categoryVO, pageNum, pageSize);
        return ResponseResultBuild.successBuild(categoryVOPage);
    }

三、修改 Rest API

3.1 修改部门

java 复制代码
/**
 * 修改部门数据
 */
@PutMapping
public Result update(@RequestBody Dept dept){
    System.out.println("修改部门数据: " + dept);
    deptService.update(dept);
    return Result.success();
}

3.2 修改分类

java 复制代码
@Slf4j
@Api(tags = "分类")
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;

@PatchMapping
    @ApiOperation(value = "修改保险分类",notes = "修改保险分类")
    @ApiImplicitParam(name = "categoryVO",value = "保险分类VO对象",required = true,dataType = "CategoryVO")
    @ApiOperationSupport(includeParameters = {"categoryVO.id","categoryVO.dataState","categoryVO.parentCategoryNo",
            "categoryVO.categoryNo","categoryVO.categoryName","categoryVO.icon","categoryVO.leafNode",
            "categoryVO.showIndex","categoryVO.categoryType","categoryVO.sortNo","categoryVO.remake","categoryVO.insuranceType",
            "categoryVO.categoryClaimVOs.claimKey","categoryVO.categoryConditionVOs.conditionKey",
            "categoryVO.categoryCoefficentVOs.coefficentKey","categoryVO.categorySafeguardVOs.safeguardKey"})
    public ResponseResult<Boolean> updateCategory(@RequestBody CategoryVO categoryVO) {
        Boolean flag = categoryService.update(categoryVO);
        return ResponseResultBuild.successBuild(flag);
    }

@RequestMapping

四、分页查询 Rest API

4.1 部门条件分页

java 复制代码
/**
* 条件分页查询
*/
@GetMapping
public Result page(EmpQueryParam param) {
    log.info("请求参数: {}", param);
    PageBean pageBean = empService.page(param);
    return Result.success(pageBean);
}
@Data
public class EmpQueryParam {

    private Integer page = 1; //页码
    private Integer pageSize = 10; //每页展示记录数
    private String name; //姓名
    private Integer gender; //性别
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate begin; //入职开始时间
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate end; //入职结束时间

}

部门分页

java 复制代码
@Slf4j
@RequestMapping("/emps")
@RestController
public class EmpController {
    @Autowired
    private EmpService empService;
    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page ,
                       @RequestParam(defaultValue = "10") Integer pageSize){
        log.info("查询员工信息, page={}, pageSize={}", page, pageSize);
        PageBean pageBean = empService.page(page, pageSize);
        return Result.success(pageBean);
    }

}

4.2 分类分页

java 复制代码
 @PostMapping("page/{pageNum}/{pageSize}")
    @ApiOperation(value = "分类分页",notes = "分类分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryVO",value = "分类VO对象",required = true,dataType = "CategoryVO"),
            @ApiImplicitParam(paramType = "path",name = "pageNum",value = "页码",example = "1",dataType = "Integer"),
            @ApiImplicitParam(paramType = "path",name = "pageSize",value = "每页条数",example = "10",dataType = "Integer")
    })
    @ApiOperationSupport(includeParameters = {"categoryVO.parentCategoryNo","categoryVO.categoryNo","categoryVO.categoryName","categoryVO.icon","categoryVO.leafNode","categoryVO.showIndex","categoryVO.categoryType","categoryVO.sortNo","categoryVO.remake","categoryVO.insuranceType"})
    public ResponseResult<Page<CategoryVO>> findCategoryVOPage(
            @RequestBody CategoryVO categoryVO,
            @PathVariable("pageNum") int pageNum,
            @PathVariable("pageSize") int pageSize) {
        Page<CategoryVO> categoryVOPage = categoryService.findPage(categoryVO, pageNum, pageSize);
        return ResponseResultBuild.successBuild(categoryVOPage);
    }

五、删除 Rest API

5.1 删除部门
方案一:通过原始的 HttpServletRequest 对象获取请求参数

java 复制代码
/**
* 根据ID删除部门 - 简单参数接收: 方式一 (HttpServletRequest)
*/
@DeleteMapping("/depts")
public Result delete(HttpServletRequest request){
    String idStr = request.getParameter("id");
    int id = Integer.parseInt(idStr);

    System.out.println("根据ID删除部门: " + id);
    return Result.success();
}

方案二:通过Spring提供的 @RequestParam 注解,将请求参数绑定给方法形参

java 复制代码
@DeleteMapping("/depts/{id}")
public Result delete(@RequestParam("id") Integer deptId){
    System.out.println("根据ID删除部门: " + deptId);
    return Result.success();
}

@RequestParam 注解的value属性,需要与前端传递的参数名保持一致 。

@RequestParam注解required属性默认为true,代表该参数必须传递,如果不传递将报错。 如果参数可选,可以将属性设置为false。

方案三:如果请求参数名与形参变量名相同,直接定义方法形参即可接收。(省略@RequestParam)

java 复制代码
@DeleteMapping("/depts/{id}")
public Result delete( @RequestParam("id") Integer id){
    System.out.println("根据ID删除部门: " + deptId);
    return Result.success();
}

5.2 删除分类

java 复制代码
 @DeleteMapping
    @ApiOperation(value = "删除分类",notes = "删除分类")
    @ApiImplicitParam(name = "categoryVO",value = "分类VO对象",required = true,dataType = "CategoryVO")
    @ApiOperationSupport(includeParameters = {"categoryVO.checkedIds"})
    public ResponseResult<Boolean> deleteCategory(@RequestBody CategoryVO categoryVO) {
        Boolean flag = categoryService.delete(categoryVO.getCheckedIds());
        return ResponseResultBuild.successBuild(flag);
    }

@RequestBody与@RequestParam区别:

  • 区别:
    @RequestParam用于接收url地址传参,表单传参【application/x-www-form-urlencoded】。
    @RequestBody用于接收json数据【application/json】。
  • 应用:
    开发中,发送json格式数据为主,@RequestBody应用较广。
    如果发送非json格式数据,选用@RequestParam接收请求参数。

六、REST介绍

RESTful介绍:

根据REST风格对资源进行访问称为RESTful。

相关推荐
代码丰10 小时前
大模型 + RAG 幻觉治理方案总结
后端
小村儿11 小时前
(译文)重温:Karpathy 的 4 条 CLAUDE.md 规则将 Claude 错误率从 41% 降至 11%——历经 30 个代码库后,我又加了 8 条
前端·后端·ai编程
user696007375661711 小时前
3个前端性能优化技巧,我用后页面加载快了80%
后端
源码集结号11 小时前
基于 Spring Boot + JPA + MySQL的上门家政系统代码示例
java·前端·后端
该用户已不存在11 小时前
别再把 Claude 当聊天框,Claude Code CLI 安装与上下文管理指北(Part 1)
后端·ai编程·claude
蝎子莱莱爱打怪11 小时前
无废话!源自官网的Codex 命令速查手册!
人工智能·后端·agent
盖世英雄酱5813611 小时前
6000条数据执行时间9s(二)
数据库·后端
是梦终空11 小时前
计算机源码273—基于SpringBoot+Vue3停车场管理系统带支沙箱支付(源代码+数据库)
数据库·spring boot·vue·mybatis·停车场管理系统·沙箱支付·毕设设计
Filwaod11 小时前
Java面试:AIGC场景下的技术深度拷问-谢飞机篇
spring boot·缓存·微服务·消息队列·aigc·java面试·ai技术
程序员老邢11 小时前
【技术底稿 32】Nginx 经典大坑复盘:本机公网域名自环代理,导致接口返回首页 / 404 实战排障
java·运维·nginx·前后端分离·技术底稿·后端部署