1. 新建 controller / BuyerProductController 类
@RestController // RestController 与 Controller 的区别可看笔记
@RequestMapping("buyer/product")
public class BuyerProductController{
@GetMapping("/list")
public ResultViewObject list(){
ResultViewObject resultViewObject = new ResultViewObject();
}
}
2. 根据约定好的 API 构造
约定的 API 格式, 大致如下
{
"code":0,
"msg":"Success",
"data":{
"name":null,
"type":null,
"foods":[
{
"id":null,
"name":null,
"price":null,
"description":null,
"icon":null
}
]
}
}
3. 返回值的结构
@Data
public class ResultViewObject<T>{
private Integer code;
private String msg;
private T data;
}
data 的结构,CategoryView
@Data
public class CategoryView<T>{
@JsonProperty("name")
private String categoryName;
@JsonProperty("type")
private String categoryType;
@JsonProperty("foods")
private List<T> categoryFoods;
}
foods 的详情,ProductInfoView
@Data
public class ProductInfoView{
@JsonProperty("id")
private String ProductId;
@JsonProperty("name")
private String ProductName;
@JsonProperty("price")
private BigDecimal productPrice;
@JsonProperty("description")
private String productDescription;
@JsonProperty("icon")
private String productIcon;
}
4. 控制层,拼装返回值 controller/BuyerProductController
@RestController
@RequestMapping("buyer/product")
public class BuyerProductController{
@GetMapping("/list")
public ResultViewObject list(){
ResultViewObject resultViewObject = new ResultViewObject();
CategoryView categoryView = new CategoryView();
List<ProductInfoView> productInfoViews = new ProductInfoView();
ProductInfoView productInfoView = new ProductInfoView();
productInfoViews.add(productInfoView);
resultViewObject.setCode("200");
resultViewObject.setMsg("success");
resultViewObject.setData(categoryView);
return ResultViewObject;
}
}
5. 配置网址头部
因为是要设计 Restful API,所以可以给网址设计一个头部的url,修改文件 application.yml
service:
servlet:
context-path: /sell