項目中採用前後端分離,使用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);
}
成功返回時:
失敗時: