如何使用Java EE應用程序實現Restlet框架?在現有Java EE應用程序中實現RESTlet
我已經嘗試過使用Spring的Restful Web服務,但不知道如何開始使用Restlet框架。
這是比Spring MVC的RESTful實現更好的選擇嗎?這兩個框架有什麼優點和缺點?
如何使用Java EE應用程序實現Restlet框架?在現有Java EE應用程序中實現RESTlet
我已經嘗試過使用Spring的Restful Web服務,但不知道如何開始使用Restlet框架。
這是比Spring MVC的RESTful實現更好的選擇嗎?這兩個框架有什麼優點和缺點?
Restlet的優勢在於它爲REST提供了完整的API,在使用REST原則時具有靈活性,並且可以解決客戶端和服務器端的問題。
您可以考慮的另一方面是Restlet是一個完整的RESTful中間件,允許使用REST架構連接各種異構系統。事實上,Restlet可以使用相同的API在多個環境(Java,Java EE,Android,GWT,Google App Engine)和雲平臺(EC2,GAE,Azure)上執行,以提供RESTful應用程序。它內部解決了每個環境的特定性和侷限性。它還允許訪問不同類型的REST服務(如OData,S3 ...),集成不同系統(AWS,Google ...)的安全性併爲Google的SDC技術提供支持(以安全的方式訪問Intranet資源) 。
現在讓我們輸入代碼。在JavaEE中實現Restlet應用程序的最佳方法是使用servlet擴展,該擴展在該應用程序中扮演前端控制器的角色。然後,您可以像往常一樣定義您的實體(Application,ServerResource)。你必須創建以下的事情:
的Restlet應用程序(子類應用):
public class ContactApplication extends Application {
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/contact/{id}",
SimpleContactServerResource.class);
return router;
}
}
一個或多個服務器資源:
public class SimpleContactServerResource
extends ServerResource {
private ContactService contactService = (...)
@Get
public Representation getContact(Variant variant) {
Map<String, Object> attributes
= getRequest().getAttributes();
String contactId = (String) attributes.get("id");
Contact contact = contactService.getContact(contactId);
return new JacksonRepresentation<Contact>(contact);
}
(...)
}
提供配置Restlet servlet:
<web-app>
<context-param>
<param-name>org.restlet.application</param-name>
<param-value>org.restlet.gtug.gae.ContactsApplication</param-value>
</context-param>
<servlet>
<servlet-name>ServerServlet</servlet-name>
<servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServerServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
希望它可以幫助你,並提供一個更好的框架視圖。