servlet只支持GET与POST两种请求。
但是restlet除了支持GET与POST请求外还支持Delete Put OPTIONS 等多种请求 。
第一步,编写资源类
(可以将资源类想象成Struts2的Action ,每个加上注解的方法都是一个ActionMethod)
MovieResource.java
- packagecom.zf.restlet.demo02.server;
- importorg.restlet.resource.Delete;
- importorg.restlet.resource.Get;
- importorg.restlet.resource.Post;
- importorg.restlet.resource.Put;
- importorg.restlet.resource.ServerResource;
- /**
- *以3中Method为例
- *@authorzhoufeng
- *
- */
- publicclassMovieResourceextendsServerResource{
- @Get
- publicStringplay(){
- return"电影正在播放...";
- }
- @Post
- publicStringpause(){
- return"电影暂停...";
- }
- @Put
- publicStringupload(){
- return"电影正在上传...";
- }
- @Delete
- publicStringdeleteMovie(){
- return"删除电影...";
- }
- }
第二步,使用html客户端访问(html默认只支持get与post访问。所以下面演示着两种)
demo02.html
- <!DOCTYPEhtml>
- <html>
- <head>
- <metacharset="UTF-8">
- <title>demo02</title>
- </head>
- <body>
- <formaction="http://localhost:8888/"method="get"target="_blank">
- <inputtype="submit"value="Get请求"/>
- </form>
- <formaction="http://localhost:8888/"method="post"target="_blank">
- <inputtype="submit"value="Post请求"/>
- </form>
- </body>
- </html>
访问该html通过两个按钮可以发送不同的请求,并会有不同的返回值
第三步:使用Restlet编写客户端调用
MovieClient.java
- packagecom.zf.restlet.demo02.client;
- importjava.io.IOException;
- importorg.junit.Test;
- importorg.restlet.representation.Representation;
- importorg.restlet.resource.ClientResource;
- publicclassMovieClient{
- @Test
- publicvoidtest01()throwsIOException{
- ClientResourceclient=newClientResource("http://localhost:8888/");
- Representationresult=client.get();//调用get方法
- System.out.println(result.getText());
- }
- @Test
- publicvoidtest02()throwsIOException{
- ClientResourceclient=newClientResource("http://localhost:8888/");
- Representationresult=client.post(null);//调用post方法
- System.out.println(result.getText());
- }
- @Test
- publicvoidtest03()throwsIOException{
- ClientResourceclient=newClientResource("http://localhost:8888/");
- Representationresult=client.put(null);//调用put方法
- System.out.println(result.getText());
- }
- @Test
- publicvoidtest04()throwsIOException{
- ClientResourceclient=newClientResource("http://localhost:8888/");
- Representationresult=client.delete();//调用delete方法
- System.out.println(result.getText());
- }
- }