2014-04-04 23 views
2

我有一個非常簡單的問題。請求/響應播放中的DTO對象

在Java代碼中,我曾經使用數據傳輸對象進行請求/響應。

例如,在我的春天的webapp,我創造了一些要求DTO,像

public class SaveOfficeRequest { 
    private String officeName; 
    private String officePhone; 
    private String officeAddress; 

    /* getters/setters */ 
} 

之後,我不得不控制器 「映射」 的方法一樣

@ResponseBody 
public SaveOfficeResponse saveOffice(@RequestBody SaveOfficeRequest) { ... } 

每個請求都是json請求。當某些控制器方法被調用時,我將請求轉換爲域dto實體並執行一些業務邏輯。

所以!

我應該在基於Play Framework的新Scala項目中保存練習嗎?

回答

1

案例類可以用來表示請求和響應對象。通過避免直接在外部接口中使用域對象,這有助於使API顯式化,形成文檔和類型安全,並隔離問題。

例如,對於一個JSON端點,控制器動作可以使用的模式是這樣的:

request.body.asJson.map { body => 
    body.asOpt[CustomerInsertRequest] match { 
    case Some(req) => { 
     try { 
     val toInsert = req.toCustomer() // Convert request DTO to domain object 
     val inserted = CustomersService.insert(toInsert) 
     val dto = CustomerDTO.fromCustomer(inserted)) // Convert domain object to response DTO 
     val response = ... // Convert DTO to a JSON response 
     Ok(response) 
     } catch { 
     // Handle exception and return failure response 
     } 
    } 
    case None => BadRequest("A CustomerInsertRequest entity was expected in the body.") 
    } 
}.getOrElse { 
    UnsupportedMediaType("Expecting application/json request body.") 
} 
+0

馬麗娟感謝,費爾南多·科雷亞! –

相關問題