Dropwizard 中使用Jersey开发Restful接口(修改、删除)

前面我们介绍了使用Jersey开发查询、新增接口,并规范了响应报文格式,如果您想了解,可以参考:

Dropwizard 中使用Jersey开发Restful接口(查询接口)icon-default.png?t=N4P3https://blog.csdn.net/m1729339749/article/details/130812817

Dropwizard 中使用Jersey开发Restful接口(响应报文格式、新增)icon-default.png?t=N4P3https://blog.csdn.net/m1729339749/article/details/130923232

本篇,我们介绍使用Jersey开发修改、删除的接口:

一、修改商品

@PUT
@Path("/{id}")
public Response update(@PathParam("id") String id, Goods goods) {
    // 查询商品
    Goods hadGoods = findById(id);
    
    // 判断商品是否存在
    if(Objects.isNull(hadGoods)) {
        return Response.ok().entity(new ResponseResult(404, "商品不存在")).build();
    }

    // 修改商品名称
    hadGoods.setName(goods.getName());
    return Response.ok().entity(new ResponseResult(0, "成功", hadGoods)).build();
}

@PUT:代表的是请求的方式、使用PUT的请求方式

@PathParam:代表的是从请求路径中获取参数

代码中对商品是否存在进行了校验,校验成功后,修改了商品的名称

测试:修改商品

请求方式:PUT

请求地址:http://localhost:8080/goods/2

请求报文:

扫描二维码关注公众号,回复: 16209450 查看本文章
{ "name": "火腿肠" }

响应结果如下:

{
    "code": 0,
    "msg": "成功",
    "data": {
        "id": "2",
        "name": "火腿肠"
    }
}

查询商品的结果如下:

{
    "code": 0,
    "msg": "成功",
    "data": [
        {
            "id": "1",
            "name": "薯片"
        },
        {
            "id": "2",
            "name": "火腿肠"
        }
    ]
}

二、删除商品

@DELETE
@Path("/{id}")
public Response delete(@PathParam("id") String id) {
    for(Iterator<Goods> it = goodsList.iterator(); it.hasNext(); ) {
        // 获取商品
        Goods goods = it.next();
        // 判断商品编号是否一致
        if(goods.getId().equals(id)) {
            // 移除商品
            it.remove();
            return Response.ok().entity(new ResponseResult(0, "成功", goods)).build();
        }
    }

    // 未找到商品
    return Response.ok().entity(new ResponseResult(404, "商品不存在")).build();
}

@DELETE:代表的是请求的方式、使用DELETE的请求方式

@PathParam:代表的是从请求路径中获取参数

测试:删除商品

请求方式:DELETE

请求地址:http://localhost:8080/goods/2

响应结果如下:

{
    "code": 0,
    "msg": "成功",
    "data": {
        "id": "2",
        "name": "可口可乐"
    }
}

查询商品的结果如下:

{
    "code": 0,
    "msg": "成功",
    "data": [
        {
            "id": "1",
            "name": "薯片"
        }
    ]
}

猜你喜欢

转载自blog.csdn.net/m1729339749/article/details/130925007