项目中采用前后端分离,使用RESTFul风格做前后端交互,但在前端获取到的数据却有很多冗余数据,造成资源的浪费,所以对项目的返回值进行统一的管理,使交互更加清晰、简单和安全。
实现思路
- 规定统一的返回实体
- 定义统一的返回类型
以一个简单的查询逻辑做示例,对Controller层进行统一的处理与封装。
@ResponseBody
@RequestMapping(value = "/getItem",method = {RequestMethod.GET} )
public ItemModel getItem(@RequestParam(name = "id")Integer id){
ItemModel itemModel = itemService.getItemById(id);
return itemModel;
}
此时返回的形式:
可以看到我们将整个的Model的值进行了返回,并且没有标识字段。
返回实体
由于前段是不需要那么多参数,所以我们可以将Model进行一层转换,只将部分有价值的字段进行封装。
在controller层中增加一层viewobject层,将需要的参数填进去,并生成其get、set方法。
public class ItemVO {
private Integer id;
//商品名称
private String title;
//商品价格
private BigDecimal price;
//商品的库存
private Integer stock;
//商品的描述
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
·········
}
对返回的itemModel转换为itemVO
private ItemVO convertVOFromModel(ItemModel itemModel) {
if(itemModel == null){
return null;
}
ItemVO itemVO = new ItemVO();
BeanUtils.copyProperties(itemModel,itemVO);
if (itemModel.getPromoModel() != null) {
itemVO.setPromoStatus(itemModel.getPromoModel().getStatus());
itemVO.setPromoId(itemModel.getPromoModel().getId());
itemVO.setStartDate(itemModel.getPromoModel().getStartDate().toString(DateTimeFormat.forPattern("yyyy-mm-dd HH:mm:ss")));
itemVO.setPromoPrice(itemModel.getPromoModel().getPromoItemPrice());
}else {
itemVO.setPromoStatus(0);
}
return itemVO;
}
返回类型
这时已经对返回的具体参数进行了一层封装,接下来对返回值进行格式的固定。
public class CommonReturnType {
//表明对应请求的返回处理结果 "success" 或 "fail"
private String status;
//若status=success,则data内返回前端需要的json数据
//若status=fail,则data内使用通用的错误码格式
private Object data;
//定义一个通用的创建方法
public static CommonReturnType create(Object result){
return CommonReturnType.create(result,"success");
}
public static CommonReturnType create(Object result,String status){
CommonReturnType type = new CommonReturnType();
type.setStatus(status);
type.setData(result);
return type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
将controller的方法进行改造,然后看一下效果。
@ResponseBody
@RequestMapping(value = "/getItem",method = {RequestMethod.GET} )
public CommonReturnType getItem(@RequestParam(name = "id")Integer id){
ItemModel itemModel = itemService.getItemById(id);
ItemVO itemVO = convertVOFromModel(itemModel);
return CommonReturnType.create(itemVO);
}
成功返回时:
失败时: