当前位置:Gxlcms > mysql > restlet2.1学习笔记(二)分别处理GetPostPut请求

restlet2.1学习笔记(二)分别处理GetPostPut请求

时间:2021-07-01 10:21:17 帮助过:49人阅读

servlet只支持GET与POST两种请求。 但是restlet除了支持GET与POST请求外还支持Delete Put OPTIONS 等多种请求 。 第一步,编写资源类 (可以将资源类想象成Struts2的Action ,每个加上注解的方法都是一个ActionMethod) MovieResource.java package com.zf.r

servlet只支持GET与POST两种请求。

但是restlet除了支持GET与POST请求外还支持Delete Put OPTIONS 等多种请求 。


第一步,编写资源类

(可以将资源类想象成Struts2的Action ,每个加上注解的方法都是一个ActionMethod)

MovieResource.java

  1. package com.zf.restlet.demo02.server;
  2. import org.restlet.resource.Delete;
  3. import org.restlet.resource.Get;
  4. import org.restlet.resource.Post;
  5. import org.restlet.resource.Put;
  6. import org.restlet.resource.ServerResource;
  7. /**
  8. * 以3中Method为例
  9. * @author zhoufeng
  10. *
  11. */
  12. public class MovieResource extends ServerResource{
  13. @Get
  14. public String play(){
  15. return "电影正在播放...";
  16. }
  17. @Post
  18. public String pause(){
  19. return "电影暂停...";
  20. }
  21. @Put
  22. public String upload(){
  23. return "电影正在上传...";
  24. }
  25. @Delete
  26. public String deleteMovie(){
  27. return "删除电影...";
  28. }
  29. }

第二步,使用html客户端访问(html默认只支持get与post访问。所以下面演示着两种)

demo02.html

  1. <meta charset="UTF-8">
  2. <title>demo02</title>

访问该html通过两个按钮可以发送不同的请求,并会有不同的返回值



第三步:使用Restlet编写客户端调用

MovieClient.java

  1. package com.zf.restlet.demo02.client;
  2. import java.io.IOException;
  3. import org.junit.Test;
  4. import org.restlet.representation.Representation;
  5. import org.restlet.resource.ClientResource;
  6. public class MovieClient {
  7. @Test
  8. public void test01() throws IOException{
  9. ClientResource client = new ClientResource("http://localhost:8888/");
  10. Representation result = client.get() ;
  11. //调用get方法
  12. System.out.println(result.getText());
  13. }
  14. @Test
  15. public void test02() throws IOException{
  16. ClientResource client = new ClientResource("http://localhost:8888/");
  17. Representation result = client.post(null) ;
  18. //调用post方法
  19. System.out.println(result.getText());
  20. }
  21. @Test
  22. public void test03() throws IOException{
  23. ClientResource client = new ClientResource("http://localhost:8888/");
  24. Representation result = client.put(null) ;
  25. //调用put方法
  26. System.out.println(result.getText());
  27. }
  28. @Test
  29. public void test04() throws IOException{
  30. ClientResource client = new ClientResource("http://localhost:8888/");
  31. Representation result = client.delete() ;
  32. //调用delete方法
  33. System.out.println(result.getText());
  34. }
  35. }

人气教程排行