春季3.0 REST:
Spring使用基于注解控制器,其可用于为一个URL绑定到控制器的方法。注解用于区分GET方法和POST方法。
@RequestMapping(value="/hotels/{hotel}/bookings/{booking}",
method=RequestMethod.GET)
public String getBooking(@PathVariable("hotel") long hotelId,
@PathVariable("booking") long bookingId, Model model) {
Hotel hotel = hotelService.getHotel(hotelId);
Booking booking = hotel.getBooking(bookingId);
model.addAttribute("booking", booking);
return "booking";
}
在引擎盖下,URI字符串中的变量“hotel”在参数列表中被转换为long,就像预订一样。 Spring REST也可以使用这种相同的技术将JSON对象封送到自定义类中。请注意,此方法注释为RequestMethod.GET
,这意味着它被调用GET请求而不是POST请求。
Spring 3.0 REST通过消除手动重新创建轮子或编组/解组Java/JSON文本的需要,可以更轻松地创建REST式Web服务。
SpringSource博客上有一个演示,标题为REST In Spring MVC。学习曲线很低,但得益于依赖关系,让演示工作可能需要一些时间。一旦你安装了并且有一个工作演示,最难的部分应该结束。
对于IDE集成,请查看Spring Roo。我没有使用它,但我听说它具有与Eclipse IDE集成的一些功能,使您的生活更轻松。
Restlets:
Restlets设计完全休息。结果,开销比Spring 3.0要低很多。 Restlets更适合您没有GUI的情况,以及您不关心MVC的情况。 Restlets可以轻松地作为服务器和客户端。它还有一个你可以运行的嵌入式服务器,它不需要像Jetty或Tomcat这样的容器。
我已经很少接触到Python,但从我看到的Google App Engine的webApp框架实现中,Router概念感觉非常相似。那些有Python背景的人可能会发现学习曲线要低得多:
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
getConnectorService().getClientProtocols().add(Protocol.FILE);
// Serve the files generated by the GWT compilation step.
Directory dir = new Directory(getContext(), LocalReference.createFileReference(new File("war/")));
router.attachDefault(dir);
router.attach("/contacts/123", ContactServerResource.class);
return router;
}
它在客户端使用GWT;我更喜欢把这部分拿出来,因为它让我想起了太多的Java Swing。虽然有些人可能会发现这种优势,但我的个人偏好是坚持那些更像Web的技术。
以下是使用独立模式的REST服务器的简单示例。服务器在端口8182上运行,并侦听GET请求。它具有与Spring REST框架类似的基于注释的模型,它还帮助分离不同的HTTP方法,并将它们指向类中的不同方法。这是一个非常基本的“Hello World” REST示例:
public class FirstServerResource extends ServerResource {
public static void main(String[] args) throws Exception {
// Create the HTTP server and listen on port 8182
new Server(Protocol.HTTP, 8182, FirstServerResource.class).start();
}
@Get
public String toString() {
return "hello, world";
}
}
退房的Restlet Web Site更多的信息和Restlets框架的例子。 Restlets的学习曲线略少于Spring,因为它的目标是REST;因此,它不包含Spring中包含的所有额外功能,有时可以使难题找到答案。如果您正在寻找轻量级的产品,Restlets绝对是您的选择。
这两个框架都将运行在Tomcat,Jetty以及Google App Engine上。
球衣看起来很有趣,会看着它!谢谢;-) – 2011-02-10 20:32:05