In the previous article, we used Jersey to develop a query interface . In this article, we modified the format of the response message and developed a new interface based on the previous article.
1. Unified response message format
We define the response message format class under the api package :
public class ResponseResult {
// 响应代码
private int code;
// 响应信息
private String msg;
// 响应数据
private Object data;
public ResponseResult(int code, String msg) {
this(code, msg, null);
}
public ResponseResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
}
2. Transform query interface
@GET
public Response find() {
return Response.ok().entity(new ResponseResult(0, "成功", goodsList)).build();
}
Test: get all items
Request method: GET
Request address: http://localhost:8080/goods
The response results are as follows:
{
"code": 0,
"msg": "成功",
"data": [
{
"id": "1",
"name": "薯片"
},
{
"id": "2",
"name": "可口可乐"
}
]
}
3. New products
@POST
public Response add(Goods goods) {
// 判断商品是否为空
if(Objects.isNull(goods)) {
return Response.ok().entity(new ResponseResult(502, "商品不能为空")).build();
}
// 判断商品编号是否为空
if(Objects.isNull(goods.getId())
|| goods.getId().isBlank()) {
return Response.ok().entity(new ResponseResult(502, "商品编号不能为空")).build();
}
// 判断商品名称是否为空
if(Objects.isNull(goods.getName())
|| goods.getName().isBlank()) {
return Response.ok().entity(new ResponseResult(502, "商品名称不能为空")).build();
}
// 根据商品编号查询商品
Goods hadGoods = findById(goods.getId());
if(Objects.nonNull(hadGoods)) {
return Response.ok().entity(new ResponseResult(502, "商品编号已经存在")).build();
}
// 添加商品
goodsList.add(goods);
return Response.ok().entity(new ResponseResult(0, "成功")).build();
}
/**
* 根据商品编号查询商品
* @param goodId 商品编号
* @return
*/
private Goods findById(String goodId) {
for (Goods g: goodsList) {
if(g.getId().equals(goodId)) {
return g;
}
}
return null;
}
@POST : Represents the request method, the request method using POST
The product, product number, product name, etc. are verified in the code
Test: add new items
Request method: POST
Request address: http://localhost:8080/goods
The response results are as follows:
{
"code": 0,
"msg": "成功",
"data": {
"id": "3",
"name": "火腿肠"
}
}
The results of the product query are as follows:
{
"code": 0,
"msg": "成功",
"data": [
{
"id": "1",
"name": "薯片"
},
{
"id": "2",
"name": "可口可乐"
},
{
"id": "3",
"name": "火腿肠"
}
]
}