【发布时间】:2012-12-03 00:51:00
【问题描述】:
这是一个设计/模式问题。我有一项服务现在也需要 公开为 RESTful Web 服务。
在现有代码中,我有一个请求的概念,一个套件 可能的 ServiceOperations(策略)和任何 ServiceOperation 的返回是 一个响应对象。这种方法解耦了 来自表示媒体的服务(自定义 TCP 服务器、HTTP REST、HTTP SOAP 等)。
我现在已经开始实现一个 MyServiceRESTfulServlet,它看起来有点像 像这样:
public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) throws ServletException, IOException {
try {
/* Wrap an http servlet request with an adapter which hides all
* the messy details of an HttpRequest and exposes a nice interface
* for working with MyService
*/
IRequest serviceRequest = new MyServiceRESTfulRequest(httpRequest);
/* There's nothing HTTP related in this part, it's the exact same
* code you'd find in other presentation formats. A Response has
* no idea about HTTP, TCP Servers or the like.
*/
Response serviceResponse = dispatchRequest(serviceRequest);
/* A static helper which knows the interface of a Response
* and can translate that into REST-speak for feeding back via
* an HttpServletResponse.
*/
renderRESTfulResponse(serviceResponse, httpResponse);
} catch (Exception e) {
throw new ServletExcetion(e); // Caught by a seperate
// RESTfulErrorServlet
// configured in web.xml
// Rendering an appropriate
// response.
}
}
我的问题是响应可以是目前两种之一:
public enum ResponseKind() {
BINARY, METADATA;
}
对于二进制,我的 restful 响应助手将呈现一种方式,用于元数据 它需要适当地呈现元数据——一个 HTML 表、一个 JSON 斑点等。
弄清楚什么类型很容易——一个 Response 对象暴露了一个 getOriginalRequest() 在适当的检查后可以转换为 MyServiceRESTfulRequest 公开一个 .getAcceptablePresentation() - 一个 枚举:
public enum RESTPresentationKind() {
HTML, JSON, XML, PROTOBUF_MYSERV_0.1;
}
我怎样才能最好地保持这个渲染代码与响应对象分离。 毫无疑问,将来可能会有其他类型的反应。照原样, renderRESTfulResponse() 遍历 Request 对象并构建 适当地写出数据。它与两者紧密耦合 响应接口(我可以接受)但它知道要通过 Request 对象也是如此。
我只是觉得我没有以干净和可维护的方式完成这一点 因为我有这项服务的其余部分。我是每个人的“特殊外壳” 可能的响应类型,以及每种可能的响应格式。感觉 超级hacky。
您能否建议任何方法来干净地处理呈现 RESTful 响应 给定一个与展示无关的 Request 对象?
【问题讨论】:
标签: java rest design-patterns servlets