27

Rest抽象得不错,把整个网站当成Resource,用post,get,put,delete四种操作来获取更新和删除Resource。

一般开发人员只用过post和get,测试了许久,put跟delete两种操作是搞不定的,有文章用jquery模拟这两种操作,其实还是用post方法,带个method参数叫put/delete。不过http是有这两种操作的,Restlet自带的客户端程序就可以实现:


Client client = new Client(Protocol.HTTP);
Reference itemsUri = new Reference("http://localhost:8182/note");
Form form = new Form();
form.add("name", "test");
Representation rep = form.getWebRepresentation();
Response response = client.put(itemsUri, rep);

服务器端也用Restlet来实现,分别对应四种操作:

实现post


public void acceptRepresentation(Representation entity) throws ResourceException

实现get


public Representation getRepresentation(Variant variant)

实现put


public void storeRepresentation(Representation entity) throws ResourceException

实现delete


public void removeRepresentations() throws ResourceException

先得提供一个方法,这样Restlet才能接收post等方法提交,不然就只有get才能成功。


public boolean isModifiable() {
return true;
}

参数Representation entity可以带入Request的参数:


Form form = new Form(entity);
String subject= form.getFirstValue("subject");
String body= form.getFirstValue("body");

不知道碰到multipart/form-data的表单会不会出问题,上传图片又如何呢?

调用rest的接口,一般采用get方法,带入method参数,例如twitter的rest api:

https://twitter.com/statuses/user_timeline.xml?id=seanwong

json格式:

https://twitter.com/statuses/user_timeline.json?id=seanwong

翻页加参数page=2。

你追随的人的信息:

https://twitter.com/statuses/friends_timeline.xml?id=seanwong

要用post方法模拟put和delete也不难,只需判断多一个参数。

在application构造方法加入


<span>getTunnelService().setMethodParameter(<span>"_method"</span><span>); </span></span>

<span><span>

客户端可以通过_method参数来模拟put和delete

<form name=”form1″ action=”<%=request.getContextPath()%>/resources/users/1?_method=put” method=”POST”>

启动Restlet自带的web服务可以省去web app的配置,写个main就可以启动webserver了:


// Create a new Restlet component and add a HTTP server connector to it
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);

// Then attach it to the local host
component.getDefaultHost().attach(new NotesApplication(component.getContext().createChildContext()));

// Now, let's start the component!
// Note that the HTTP server connector is also automatically started.
component.start();

启动自带的server,测试起来还是比较方便的。

如twitter的链接,可以部署下:


public Restlet createRoot() {
Router router = new Router(this.getContext());

router.attach(&quot;/statuses/friends_timeline.xml&quot;, XMLResource.class);
router.attach(&quot;/statuses/friends_timeline.json&quot;, JSONResource.class);

return router;
}

参考:

http://bitworking.org/projects/URI-Templates/

http://ajaxcn.javaeye.com/

http://oracleseeker.com/2008/10/22/extending_restlet_application_support_create_update_resource/

Tagged with:
preload preload preload