2014-04-04 2 views
2

나는 아주 간단한 질문이 있습니다.요청/응답 Play의 DTO 개체

Java 코드에서 필자는 요청/응답에 데이터 전송 개체를 사용했습니다.

예를 들어, 내 봄 웹 애플리케이션에 난 내가

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

처럼 "매핑"방법 컨트롤러했다 그 후

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

    /* getters/setters */ 
} 

같은 일부 요청 DTO를 작성했다.

모든 요청은 json 요청입니다. 어떤 컨트롤러 메소드가 호출 될 때 요청 dto를 도메인 엔티티로 변환하고 비즈니스 로직을 수행합니다.

그래서!

Play Framework를 기반으로하는 새로운 스칼라 프로젝트에서 연습을 저장해야합니까?

답변

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

Greate 덕분에, 페르난도 코레! –