开发实例一基于JAXRS的REST服务_第1页
开发实例一基于JAXRS的REST服务_第2页
开发实例一基于JAXRS的REST服务_第3页
开发实例一基于JAXRS的REST服务_第4页
开发实例一基于JAXRS的REST服务_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、RESTLET开发实例(一)基于JAX-RS的REST服务RESTLET介绍Restlet项目为“建立REST概念与Java类之间的映射”提供了一个轻量级而全面的框架。它可用于实现任何种类的REST式系统,而不仅仅是REST式Web服务。Restlet项目受到Servlet API、JSP(Java Server Pages)、HttpURLConnection及Struts等Web开发技术的影响。该项目的主要目标是:在提供同等功能的同时,尽量遵守Roy Fielding博士论文中所阐述的REST的目标。它的另一个主要目标是:提出一个既适于客户端应用又适于服务端的应用的、统一的Web视图。Re

2、stlet的思想是:HTTP客户端与HTTP服务器之间的差别,对架构来说无所谓。一个软件应可以既充当Web客户端又充当Web服务器,而无须采用两套完全不同的APIs。准备工作1、Restlet提供了多个版本:Java SE、Java EE、android、Google AppEngine、Google Web Toolkit、Android。这里我们下载jee版本。restlet-jee-.zip 下载地址:2、restlet-jee-.zip解压到硬盘,这里以%RESTLET_HOME%表示为解压的文件目录。一、基于JAX-RS的REST服务JAX-RS (JSR-311) 是一种 Java

3、 API,可使 Java Restful 服务的开发变得迅速而轻松。这个 API 提供了一种基于注释的模型来描述分布式资源。注释被用来提供资源的位置、资源的表示和可移植的(pluggable)数据绑定架构。在本文中,学习如何使用 JAX-RS 在 Java EE 环境内实现 RESTful 服务架构的潜能。1、新建java web project RestService工程2、%RESTLET_HOME%lib 复制到 RestServiceWebRootWEB-INFlib 下,并加入工程引用。为了测试方便可以将全部的lib包加入进去。实际上面,你可以根据实际需要只复制相应的包进去即可。下面

4、的图片是我加入的相关的jar包:这个是必须的,如果是用于JAX-RS发布rest的话,还需要这几个包:3、创建Student实体类,用于返回数据。Student使用JAXB绑定技术,自动解析为xml返回给客户端或浏览器。JAXB是一套自动映射XML和Java实例的开发接口和工具。JAXB使XML更加方便的编译一个XML SCHEMA到一个或若干个JAVA CLASS。可以从使用JAXB 进行数据绑定  获得详细介绍。XmlRootElement(name=”Student”)public class Student   private int id; p

5、rivate String name; private int sex; private int clsId; private int age;  public int getId()   return id;  public void setId(int id)   this.id = id;  public String getName()   return name;  public void setName(Strin

6、g name)    = name;  public int getSex()   return sex;  public void setSex(int sex)   this.sex = sex;  public int getClsId()   return clsId;  public void setClsId(int clsId)   this.clsId = clsId; &

7、#160;public int getAge()   return age;  public void setAge(int age)   this.age = age; 4、Restlet架构主要是Application和Resource的概念。程序上可以定义多个Resource,一个Application可以管理多个Resource。创建应用类:StudentApplication 继承了抽象类:,并重载getClasses()方法。代码如下:Set<Class<?>> rrcs = new Ha

8、shSet<Class<?>>();rrcs.add(StudentResource.class);绑定了StudentResource。有多个资源可以在这里绑定。你可以有Course等其他更多资源,相应的可以定义为:CourseResource及Course,然后加入rrcs.add(CourseResource.class)。创建资源类:StudentResource管理Student实体类Path(“student”)public class StudentResource       GET  

9、;   Path(“id/xml”)     Produces(“application/xml”)     public Student getStudentXml(PathParam(“id”) int id)    return ResourceHelper.getDefaultStudent();     其中:Path(“student”)执行了uri路径,student路径进来的都会调用StudentResource来处理。

10、GET 说明了http的方法是get方法。Path(“id/xml”) 每个方法前都有对应path,用来申明对应uri路径。Produces(“application/xml”) 指定返回的数据格式为xml。PathParam(“id”) int id  接受传递进来的id值,其中id为 id定义的占位符要一致。和上面类似,我们可以定义返回json格式方法,如下GETPath(“id/json”)Produces(“application/json”)public Student getStudentJson(PathParam(“id”) int id)   return

11、 ResourceHelper.findStudent(id);其中:Produces(“application/json”)  指定返回的数据格式为json。5、定义了相应的Resource和Application后,还要创建运行环境。RESTlet 架构为了更好的支持 JAX-RS 规范,定了 JaxRsApplication 类来初始化基于 JAX-RS 的 Web Service 运行环境。创建运行类:RestJaxRsApplication  继承了类:。构造方法代码如下:public RestJaxRsApplication(Context context) &

12、#160;super(context); this.add(new StudentApplication();将StudentApplication加入了运行环境中,如果有多个Application可以在此绑定。二、发布和部署restlet服务1、将Restlet服务部署到 Tomcat容器中web.xml加入如下代码:<context-param> <param-name>org.restlet.application</param-name> <param-value>ws.app.RestJaxRsApplic

13、ation</param-value></context-param><servlet> <servlet-name>RestletServlet</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class></servlet><servlet-mapping> <servlet-name>RestletServlet</servlet

14、-name> <url-pattern>/*</url-pattern></servlet-mapping>启动tomcat没报错的话,说明你配置正常。2、将Restlet服务当做单独的Java 程序进行部署创建类 RestJaxRsServer,代码如下:public static void main(String args) throws  Exception  Component component = new Component(); component.getServers().add(Protocol

15、.HTTP, 8085);         component.getDefaultHost().attach(new RestJaxRsApplication(null); component.start(); 该类中创建一个新的 Http Server,添加监听端口8085。将RestJaxRsApplication加入到 Http Server 中。运行该代码,下图说明你启动成功。三、测试Restlet服务1、浏览器模式访问xml数据http:/localhost:8085/Re

16、stService/student/1/xml访问json数据http:/localhost:8085/RestService/student/1/json  提示下载数据,下载后打开数据内容为“name”:”Steven”,”id”:1,”age”:0,”sex”:1,”clsId”:201001如果是独立部署的话,直接访问:http:/localhost:8085/student/1/xml即可。2、Restlet自带了客户端测试代码,目前提供了jee、webkit、android等版本,调用rest服务,非常方便。新建Client类,代码如下:/public static St

17、ring url=”http:/localhost:8085/“; public static String url=”http:/localhost:8085/RestService/“;public static void testXml()  ClientResource client = new ClientResource(url+”student/1/xml”); try   System.out.println(client.get().getText();  catch (ResourceException e) &#

18、160; / TODO Auto-generated catch block  e.printStackTrace();  catch (IOException e)   / TODO Auto-generated catch block  e.printStackTrace(); public static void testJson()  ClientResource client = new ClientResource(url+”student/1/json”); try &#

19、160; System.out.println(client.get().getText();  catch (ResourceException e)   / TODO Auto-generated catch block  e.printStackTrace();  catch (IOException e)   / TODO Auto-generated catch block  e.printStackTrace(); 通过junit测试代码分别输出:四、实现对Res

20、t服务的PUT,POST,DELETE方法。到现在我们已经完成一个基本的Rest搭建,并且实现了GET方法。REST定义了4个基本方法:可以参见REST架构概述。1、POST方法在StudentResource中加入该方法,用于添加一个Student:POSTPath(“add”)public String addStudent(Representation entity)   Form form = new Form(entity);  String name = form.getFirstValue(“name”);  int clsId = Integer.

21、parseInt(form.getFirstValue(“clsId”);  int sex = Integer.parseInt(form.getFirstValue(“sex”);  Student student = new Student();  student.setClsId(clsId);  student.setName(name);  student.setSex(sex);  ResourceHelper.maxId+;  int id =  ResourceHelper.maxId; 

22、; student.setId(id);  return String.valueOf(ResourceHelper.addStudent(student);POST 说明这是个post方法调用,如果是用restlet客户端调用的话,调用client.post(form.getWebRepresentation()方法,如果是网页上面操作的话,就是一个标准的post方法。Representation entity:Restlet中全部的接受和返回对象都Representation类的子类。将entity 封装为Form对象,就可以通过Form取得post过来的数据。相应的客户端调用代

23、码:public static void testPost() ClientResource client = new ClientResource(url+”student/add”);try  Form form = new Form(); form.add(“name”, “lifeba”); form.add(“clsId”,”201001); form.add(“sex”,”0); String id = client.post(form.getWebRepresentation().getText(); System.ou

24、t.println(id);  catch (Exception e)  / TODO Auto-generated catch block e.printStackTrace();将需要传递的参数封装为Form对象,然后通过post(form.getWebRepresentation()来调用服务端post方法,返回时添加成功的Student的id。添加成功后,访问:http:/localhost:8085/RestService/student/2/xml  如下图:除了上面的通过restlet提供的客户端调用外,你也可以直接通过网页的post数据过

25、来。新建java web project RestServiceForm工程,添加add.jsp。<form action=”/RestService/student/add” method=”post”>     用户名:<input type=”text” name=”name”><br>     班级:<input type=”text” name=”clsId”><br>     性别:<input t

26、ype=”text” name=”sex”><br>     <input type=”submit” value=”提交”></form>提交成功后:测试新添加的student数据:2、PUT方法PUT方法用来更新一个Student对象,和上面的POST方法类似。需要注意的地方,如果是通过restlet客户端接口来调用的话,必须使用client.put(form.getWebRepresentation()方法。主要代码如下:PUTPath(“update”)public String updateStuden

27、t(Representation entity)   Form form = new Form(entity);  int id = Integer.parseInt(form.getFirstValue(“id”);  Student student = ResourceHelper.findStudent(id);   String name = form.getFirstValue(“name”);  int clsId = Integer.parseInt(form.getFirstValue(“clsId”); 

28、int sex = Integer.parseInt(form.getFirstValue(“sex”);   student.setClsId(clsId);  student.setName(name);  student.setSex(sex);   return String.valueOf(ResourceHelper.updateStudent(student);Restlet客户端调用代码,对id为1的student进行编辑。public static void testUpdate()  ClientReso

29、urce client = new ClientResource(url+”student/update”); try   Form form = new Form();  form.add(“name”, “steven2);  form.add(“clsId”,”201002);  form.add(“sex”,”0);  form.add(“id”,”1);  String id = client.put(form.getWebRepresentation()

30、.getText();  System.out.println(id);    catch (Exception e)   / TODO Auto-generated catch block  e.printStackTrace(); 执行后访问http:/localhost:8085/RestService/student/1/xml:那么我们如何从网页中直接调用put接口呢?form只有get和post方法,并没有put和delete的对应方法。Restlet为我们提供了method指定操作

31、的支持。要在form中执行同样的操作,只需加入method=put即可,可以通过url直接拼接,或者post中加入隐藏input。这里如果直接拼接URL来实现,代码如下:<form action=”/RestService/student/update?method=put” method=”post”> 用户ID:<input type=”text” name=”id” ><br> 用户名:<input type=”text” name=”name”><br> 班级:<input type=”text” name=”clsId”><br> 性别:<input type=”text” name=”sex”><br> <input typ

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论