JAX-RS 方式的 RESTful Web Service 开发

JAX-RS 方式的 RESTful Web Service 开发

                                                                          ——基于 CXF+Spring 的实现

Web Service 目前在风格上有两大类,一个是基于 SOAP 协议,一个是完全遵循 HTTP 协议规范的 RESTful 风格。 SOAP 方式的 web service 已经很成熟了,应用也很广,已经成为 Web Service 的工业标准。不过 RESTful Web Service 现在势头越来越猛,特别是其灵活性以及与 Ajax 的完美结合,让人爱不释手,很有必要了解一下。 RESTful 就是一种架构风格,是对 HTTP 协议的完全遵循。像是人们经历了无止境的对 HTTP 引申、扩展之路后的一种回归,让 web service 开发者重新做回 HTTP 协议的信徒。 RESTful 倡导用 HTTP 协议中的 verb 与实际数据操作的增删改查相对应,如 HTTP 中的 PUT 、 GET 、 POST 、 DELETE 分别对应 web 系统中数据的改、查、增、删的操作。当然 RESTful 支持的 http verb 还不仅限于上述 4 个,还有像其他的 HEAD,OPTION ……等,不过上述 4 个已经够我们日常使用了。

目前 Web Service 的框架很多,不过我只用过 CXF ,所以我还是以 apache-cxf2.2.2 为例介绍一下 RESTful Web Service 的开发。

比较常见的 RESTful Web Service 的发布有 JAX-RS 风格、 Provider 方式、 Servlet 方式、 HTTPBinding ,也许还有其他方式,不过我只知道这些了。总的感觉最偷懒的方式是采用 Servlet 方式发布 Web Service ,说是 Web Service 发布,其实就是转换下对 Servlet 的认识, Servlet 本身就支持对 HTTP 请求中各种动作的支持,所以 Servlet 原生就是一种 RESTful Web Service 。不过这种方式我觉得有些不够时尚。 Povider 的方式我了解了一下,需要实现 Provider 接口,感觉很受拘束。正在我对 RESTful 丧失兴趣的时候,发现了 JAX-RS 风格, JAX-RS 就像是一个清纯 MM ,服务端配置完成,而且配置非常的清秀。而且也非常的平易近人,客户端调用方式很灵活。接下来我就把她介绍给大家。

1.      环境搭建

在本示例中采用了 Web Project 的方式, Web 工程建立的过程就不再赘述了,只列举一下环境需要的 jar 包。如下:

下面是我本地工程中的 jar ,仅供参考。

环境信息

注:如果要在 RESTful 服务中直接返回 json 数据格式的话, jsr311-api-1.0.jar 必不可少。

2.      服务开发

我们以简单的一个客户信息服务为例进行介绍。服务的业务实现大家不用太在意,关注服务开发的过程就好了。

2.1   开门见山

首先我们先构造一个客户的 VO 。

Java代码  收藏代码
  1. package com.harvey.cxf.demo.rest.rs.vo;  
  2.   
  3. import javax.xml.bind.annotation.XmlAccessType;  
  4. import javax.xml.bind.annotation.XmlAccessorType;  
  5. import javax.xml.bind.annotation.XmlRootElement;  
  6.   
  7. @XmlRootElement(name = "Customer")  
  8. @XmlAccessorType(XmlAccessType.FIELD)  
  9. public class Customer {  
  10.     private long id;  
  11.     private String name;  
  12.   
  13.     public long getId() {  
  14.         return id;  
  15.     }  
  16.   
  17.   
  18.     public void setId(long id) {  
  19.         this.id = id;  
  20.     }  
  21.   
  22.     public String getName() {  
  23.         return name;  
  24.     }  
  25.   
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29. }  

接下来以 CustomerService 作为客户服务的实现类

先以最常见的查询某一客户信息为例,如下:

Java代码  收藏代码
  1. @Path("/")  
  2. public class CustomerService {  
  3.     ……  
  4.    //普通路径参数方式GET请求  
  5.     @GET  
  6.     @Path("/customers/{id}")  
  7.     public Customer getCustomer(@PathParam("id") String id) {  
  8.         ……  
  9.     }  
  10. }  

假设我们的服务最终发布地址为 http://127.0.0.1:8080/customerservice 的话,如果要查询某一客户的信息的话,我们只需发送 GET 请求 http://127.0.0.1:8080/customerservice/customers/123 ,或者直接在浏览器中输入该 url 就可直接访问该服务。其中 url 中传入的 123 会自动适配到服务中的 {id} 参数。这样一个简单的处理 GET 请求的 RESTful Web service 就开发完了。

2.2 参数处理

在上面的例子中我们看到, client 在服务请求时传递参数是通过的请求路径的方式传入的。如之前的http://127.0.0.1:8080/customerservice/customers/123 , 客户 ID123 作为了路径一部分。对应的服务器端的参数配置采用了 @PathParam ( "id" ) String id 。 
除了支持路径传递的方式之外,我们还可以在请求时的查询参数中指定。比如还是查询某一客户的信息, server端代码可以如下:

Java代码  收藏代码
  1. ……  
  2. @GET  
  3.     @Path("/customers/getCustomerById")  
  4.     public Customer getCustomerByQueryString(@QueryParam("id") String id){  
  5.        ……  
  6.     }  

此时该服务访问 url 则为:

http://127.0.0.1:8080/customerservice/customers/getCustomerById?id=123

说着这,也许会有听众要问了(也许没人问):之前提到的都是简单参数,这个容易,那么对于一些复杂 bean 参数该怎么处理呢?

这个问题问得好,接下来我就举例说明下。说例子之前再重复一遍啊,看例子时千万不要纠结于代码的业务逻辑,只看技术实现方式。

Java代码  收藏代码
  1. ……  
  2. @GET  
  3.     @Path("/customers/getCust")  
  4.     public Customer getCustomer(@QueryParam("")Customer cust) {  
  5.         ……  
  6. }  

这个例子中需要传入之前声明的客户信息类作为参数。参数处理方式为 QueryParam ,所以这时候我们访问 url 格式类似以下:

http://127.0.0.1:8080/customerservice/customers/getCust?id=123&name=xiaoming

如果参数 bean 还包括其他属性,用 & 符号依次追加就好了。还通常的 web 访问没什么区别。

如果你觉得上述用查询字串的方式不够个性的话,可以采用另外一种: @MatrixParam

Server 端代码如下:

Java代码  收藏代码
  1. ……  
  2. @GET  
  3.     @Path("/customers/getCustByMat")  
  4.     public Customer getCustomerByMat(@MatrixParam("")Customer cust) {  
  5.         ……  
  6. }  

这时候我们再访问时就可以用下面的形式了:

http://127.0.0.1:8080/customerservice/customers/getCustByMat;id=123;name=xiaoming

如果 cusmomer 还有其他属性,直接在后面追加就可以了,参数之间用 ; 分隔 .

以上我们用到的参数虽然采用的处理方式的注解各不相同,但是都是有注解的。接下来出场的这个就属于特殊人物了。有请 body 参数出场……

  

Java代码  收藏代码
  1. ……  
  2. @POST  
  3.     @Path("/addCustomer")  
  4.     public Customer addCustomer(String body) {  
  5.     ……  
  6. }  

这个 body 参数是 JAX-RS 中比较特殊的,它前面没有任何注解,它代表的是请求的 body 内容或者请求的inputstream ,自动解析映射为字符串参数。因为之前我们的例子都是 GET 请求,消息中是没有 body 的,所以细心的听众可能会发现我们这次的服务的 verb 配置为了 @POST 。

2.3 请求、应答数据格式

之前的示例中我们的方法都返回了 Customer ,但是我们的系统是一个 RESTful web service 啊,客户端接收到的肯定是一个 HTTP 的 response 消息,那么返回的 Customer 是怎样的一个消息内容呢?

默认情况下 reponse 消息的 Customer 会以 xml 的格式返回。类似于:

<Customer><id>123</id><name>skdjl</name></Customer>

客户端调用 server 端服务,得到上述的 xml 字串结果,然后进行后续处理。

既然这说的默认情况,言外之意就是说还有很多其他情况了,不过需要配置一下。就不得不说下@Produces注解了。@Produces就是表示server端返回的数据格式类型,具体包括application/xml, application/json, application/text……,其实就是我们常见的web端的content-type中的类型。如果我们设置为application/json,自然返回的数据格式为json形式。另一个注解:@Consumes,就是与@Produces相对应的。@Consumes是设定的客户端发送的请求数据的格式,对应支持的类型与@Produces相同。具体配置如下:

Java代码  收藏代码
  1. ……  
  2. @POST  
  3.     @Path("/addCustomerUseBean")  
  4.     @Produces("application/json")  
  5.     @Consumes("application/xml")  
  6.     public Customer addCustomerUseBean(Customer cust) {  
  7.         ……  
  8.     }  

         这个例子的意思是客户端传入 Customer 作为参数,传递格式为 xml 风格, server 端应答的数据格式为 json风格。我们当然也可以在类注解中加入 @Produces 和 @Consumes 作为服务整体的 request 和 response 风格,具体服务方法如果不设定的话采用类的 @Produces 和 @Consumes 的设定。

3        服务配置

服务开发完成之后,我们要做的就是把服务发布出去。发布方式也很灵活,可以采用编码的方式,也可以和 spring 结合用配置的方式。在下面的例子中我们采用后者。配置的内容不再做过多的解释,大家看一下就能明白。

3.1   web.xml 的配置

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <web-app version="2.4"  
  4.          xmlns="http://java.sun.com/xml/ns/j2ee"  
  5.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
  7.          http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  8.   
  9.          <display-name>DEMO</display-name>  
  10.          <context-param>  
  11.                    <param-name>contextConfigLocation</param-name>  
  12.                    <param-value>classpath*:/applicationContext*.xml</param-value>  
  13.          </context-param>  
  14.   
  15.          <listener>  
  16.                   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  17.          </listener>  
  18.   
  19.          <listener>  
  20.          <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  21.          </listener>  
  22.   
  23.          <servlet>  
  24.                  <servlet-name>CXFServlet</servlet-name>  
  25.                  <servlet-class>  
  26.                           org.apache.cxf.transport.servlet.CXFServlet  
  27.                  </servlet-class>  
  28.                  <load-on-startup>1</load-on-startup>  
  29.           </servlet>  
  30.   
  31.          <servlet-mapping>  
  32.                  <servlet-name>CXFServlet</servlet-name>  
  33.                  <url-pattern>/services/*</url-pattern>  
  34.           </servlet-mapping>  
  35.   
  36.   <welcome-file-list>  
  37.     <welcome-file>index.jsp</welcome-file>  
  38.   </welcome-file-list>  
  39. </web-app>  

 

3.2   spring 配置文件

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans  
  4.          xmlns="http://www.springframework.org/schema/beans"  
  5.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.          xmlns:aop="http://www.springframework.org/schema/aop"  
  7.          xmlns:cxf="http://cxf.apache.org/core"  
  8.     xmlns:jaxws="http://cxf.apache.org/jaxws"  
  9.     xmlns:jaxrs="http://cxf.apache.org/jaxrs"  
  10.   
  11.          xsi:schemaLocation="  
  12.          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  13.          http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd  
  14.          http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd  
  15.          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">  
  16.   
  17.          <import resource="classpath:META-INF/cxf/cxf.xml" />  
  18.          <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
  19.          <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  20.          <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>  
  21.   
  22.    <jaxrs:server id="customerService" address="/customerservice">  
  23.                    <jaxrs:serviceBeans>  
  24.           <ref bean="customerServiceBean"/>  
  25.         </jaxrs:serviceBeans>  
  26.    </jaxrs:server>  
  27.    <bean id="customerServiceBean" class="com.harvey.cxf.demo.rest.rs.server.CustomerService"/>  
  28. </beans>  

 

然后启动我们的 web 程序,服务就发布完成了。可以在浏览器中敲入:

http://127.0.0.1:8080/customerservice/customers/1 测试服务是否正常。

从上面的例子也许你能发现,我们虽然是做的RESTful的例子,但是具体提供的服务verb中很多都是带有动作的成分比如getCustomer,addCustomer等等,这些词汇的存在预示着我们的服务虽然采用了RESTful的技术,但是并没有遵循ROA(面向资源的架构)的理念,真正的ROA信徒看到上面的例子可能会非常不爽。因为毕竟RESTful和ROA才是青梅竹马。不过正如前面提到的,大家值关注技术实现就好了。

4        客户端调用

我们的服务发布完成了,接下来我们可以做一个测试 client 程序进行 测试。对于 RESTful 的调用方式很多,可以用 java 的 Connect 方式,也可以用 apche 的 httpclint ,另外还可以用 cxf 提供的 WebClient 进行,等等。后面的 client 代码中分别采用几种调用方式,在这里我们不必拘泥,可以任意选用自己熟悉的方式。代码详见第 5 节。

原文地址:https://www.cnblogs.com/Rozdy/p/4479725.html