zoukankan      html  css  js  c++  java
  • 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视图。
    Restlet的思想是:HTTP客户端与HTTP服务器之间的差别,对架构来说无所谓。一个软件应可以既充当Web客户端又充当Web服务器,而无须采用两套完全不同的APIs。

    准备工作

    1、Restlet提供了多个版本:Java SE、Java EE、android、Google AppEngine、Google Web Toolkit、Android。
    这里我们下载jee版本。
    restlet-jee-2.0.6.zip 下载地址:http://www.restlet.org/downloads/2.0/restlet-jee-2.0.6.zip

    2、restlet-jee-2.0.6.zip解压到硬盘,这里以%RESTLET_HOME%表示为解压的文件目录。

    一、基于JAX-RS的REST服务

    JAX-RS (JSR-311) 是一种 Java API,可使 Java Restful 服务的开发变得迅速而轻松。这个 API 提供了一种基于注释的模型来描述分布式资源。注释被用来提供资源的位置、资源的表示和可移植的(pluggable)数据绑定架构。在本文中,学习如何使 用 JAX-RS 在 Java EE 环境内实现 RESTful 服务架构的潜能。

    1、新建java web project RestService工程

    2、%RESTLET_HOME%lib 复制到 RestServiceWebRootWEB-INFlib 下,并加入工程引用。为了测试方便可以将全部的lib包加入进去。实际上面,你可以根据实际需要只复制相应的包进去即可。下面的图片是我加入的相关的jar包:

    org.restlet.jar这个是必须的,如果是用于JAX-RS发布rest的话,还需要这几个包:
    javax.ws.rs.jar
    javax.xml.bind.jar
    org.json.jar
    org.restlet.ext.jaxrs.jar
    org.restlet.ext.json.jar
    org.restlet.ext.servlet.jar

    3、创建Student实体类,用于返回数据。Student使用JAXB绑定技术,自动解析为xml返回给客户端或浏览器。

    JAXB是一套自动映射XML和Java实例的开发接口和工具。JAXB使XML更加方便的编译一个XML SCHEMA到一个或若干个JAVA CLASS。可以从
    使用 JAXB 进行数据绑定  获得详细介绍。

    @XmlRootElement(name="Student")
    public class Student {

    private int id;
    private 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(String name) {
    this.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;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    }

    4、Restlet架构主要是Application和Resource的概念。程序上可以定义多个Resource,一个Application可以管理多个Resource。

    创建应用类:StudentApplication 继承了抽象类:javax.ws.rs.core.Application,并重载getClasses()方法。代码如下:

    Set<Class<?>> rrcs = new HashSet<Class<?>>();
    rrcs.add(StudentResource.class);

    绑定了StudentResource。有多个资源可以在这里绑定。你可以有Course等其他更多资源,相应的可以定义为:CourseResource及Course,然后加入rrcs.add(CourseResource.class)。

    创建资源类:StudentResource管理Student实体类

    @Path("student")
    public class StudentResource {

    @GET
    @Path("{id}/xml")
    @Produces("application/xml")
    public Student getStudentXml(@PathParam("id") int id) {
    return ResourceHelper.getDefaultStudent();
    }
    }

    其中:
    @Path("student")执行了uri路径,student路径进来的都会调用StudentResource来处理。
    @GET 说明了http的方法是get方法。
    @Path("{id}/xml") 每个方法前都有对应path,用来申明对应uri路径。
    @Produces("application/xml") 指定返回的数据格式为xml。
    @PathParam("id") int id  接受传递进来的id值,其中id为 {id}定义的占位符要一致。
    和上面类似,我们可以定义返回json格式方法,如下

    @GET
    @Path("{id}/json")
    @Produces("application/json")
    public Student getStudentJson(@PathParam("id") int id) {
    return ResourceHelper.findStudent(id);
    }

    其中:
    @Produces("application/json")  指定返回的数据格式为json。

    5、定义了相应的Resource和Application后,还要创建运行环境。RESTlet 架构为了更好的支持 JAX-RS 规范,定了 JaxRsApplication 类来初始化基于 JAX-RS 的 Web Service 运行环境。

    创建运行类:RestJaxRsApplication  继承了类:org.restlet.ext.jaxrs.JaxRsApplication。构造方法代码如下:

    public RestJaxRsApplication(Context context) {
    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.RestJaxRsApplication</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-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.HTTP, 8085);
    component.getDefaultHost().attach(new RestJaxRsApplication(null));
    component.start();
    }

    该类中创建一个新的 Http Server,添加监听端口8085。将RestJaxRsApplication加入到 Http Server 中。运行该代码,下图说明你启动成功。

    三、测试Restlet服务

    1、浏览器模式

    访问xml数据 http://localhost:8085/RestService/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 String 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) {
    // 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 {
    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测试代码分别输出:

    四、实现对Rest服务的PUT,POST,DELETE方法。

    到现在我们已经完成一个基本的Rest搭建,并且实现了GET方法。REST定义了4个基本方法:可以参见 REST架构概述

    1、POST方法

    在StudentResource中加入该方法,用于添加一个Student:

    @POST
    @Path("add")
    public String addStudent(Representation entity) {
    Form form = new Form(entity);
    String name = form.getFirstValue("name");
    int clsId = Integer.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;
    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过来的数据。
    相应的客户端调用代码:

    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.out.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数据过来。

    新建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 type="text" name="sex"><br>
    <input type="submit" value="提交">
    </form>

    提交成功后:

    测试新添加的student数据:

    2、PUT方法

    PUT方法用来更新一个Student对象,和上面的POST方法类似。需要注意的地方,如果是通过restlet客户端接口来调用的话,必须使用client.put(form.getWebRepresentation())方法。主要代码如下:

    @PUT
    @Path("update")
    public String updateStudent(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"));
    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() {
    ClientResource 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()).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指定操作的支持。要在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 type="submit" value="提交">
    </form>

    执行成功后可以看到student为1的数据已经成功修改:

    3、DELETE方法

    和PUT、POST方法一样,主要代码如下:

    @DELETE
    @Path("delete/{id}")
    public String deleteStudent(@PathParam("id") int id) {
    int status = ResourceHelper.deleteStudent(id);
    return String.valueOf(status);
    }

    Restlet客户端调用代码,这里删除2次,第一次返回1,说明删除成功,第二次返回0,说明该student已经删除了,所以返回0,没有找到该Student。

    public static void testDelete() {
    ClientResource client = new ClientResource(url+"student/delete/1");
    try {
    System.out.println(client.delete().getText());
    System.out.println(client.delete().getText());
    } catch (ResourceException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    通过网页的删除和上面的put类似,这里就不再说明了。

    好了,到这里已经实现了GET、PUT、POST、DELETE 四个rest的基本操作。其中要注意的是,通过GET、DELETE 来操作的话,如果是调用Restlet客户端,是不传递Representation entity的,直接通过uri的占位符来传递id来操作。REST调用接口通过标准的HTTP接口来实现,Restlet返回的标准的xml、json 格式。实现了跨客户端的调用。Restlet提供了android,webkit客户端调用支持,使用起来更加方便。

    下一篇文章介绍了非JAX-RS模式的Rest开发,构建一个更通用的Rest服务,RESTLET开发实例(二)使用Component、Application的REST服务

    五、相关工程资源下载

    RestService工程

    RestServiceForm工程

  • 相关阅读:
    编写高质量Python程序(四)库
    编写高质量Python程序(三)基础语法
    编写高质量Python程序(二)编程惯用法
    编写高质量Python程序(一)基本准则
    IM聊天教程:发送图片/视频/语音/表情
    微信小程序使用GoEasy实现websocket实时通讯
    Websocket直播间聊天室教程
    不将就!GoEasy消息推送助力一加手机8系线上发布会
    手把手教你用GoEasy实现Websocket IM聊天
    Uniapp使用GoEasy实现websocket实时通讯
  • 原文地址:https://www.cnblogs.com/duanxz/p/3596496.html
Copyright © 2011-2022 走看看