Web Service与Apache CXF 框架

一、WebService简介

  为了支持跨网络的机器间相互操作交互而设计,用于开发分布式的互操作的应用程序组件。

  Web Service服务通常被定义为一组模块化的API,它们可以通过网络进行调用,来执行远程系统的请求服务,而XML 是 Web Services 的基础。

二、快速入门

  • 将${JDK}\bin目录添加到path环境变量
  • 新建一个文件夹,打开命令行,并cd到该目录
  • 执行命令
  • wsimport -s . http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl
  • 新建Java工程,将文件夹下的内容拷贝到src目录
  • 创建测试类,测试功能
  • 1 public class TestService {
    2    public static void main(String[] args) {
    3        MobileCodeWS mobileCodeWS = new MobileCodeWS();
    4        MobileCodeWSSoap soap = mobileCodeWS.getMobileCodeWSSoap();
    5        String info = soap.getMobileCodeInfo("1886666", "");
    6        System.out.println(info);
    7    }
    8 }

三、SOAP(imple Object Access Protocol)

  使用HTTP协议传输XML格式的数据。

  • SOAP请求示例
     1 POST /InStock HTTP/1.1
     2 Host: www.example.org
     3 Content-Type: application/soap+xml; charset=utf-8
     4 Content-Length: nnn
     5 
     6 <?xml version="1.0"?>
     7 <soap:Envelope
     8 xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
     9 soap:encoding>
    10 
    11 <soap:Body xmlns:m="http://www.example.org/stock">
    12   <m:GetStockPrice>
    13     <m:StockName>IBM</m:StockName>
    14   </m:GetStockPrice>
    15 </soap:Body>
    16 
    17 </soap:Envelope>
  • SOAP响应示例

  •  1 HTTP/1.1 200 OK
     2 Content-Type: application/soap+xml; charset=utf-8
     3 Content-Length: nnn
     4 
     5 <?xml version="1.0"?>
     6 <soap:Envelope
     7 xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
     8 soap:encoding>
     9 
    10 <soap:Body xmlns:m="http://www.example.org/stock">
    11   <m:GetStockPriceResponse>
    12     <m:Price>34.5</m:Price>
    13   </m:GetStockPriceResponse>
    14 </soap:Body>
    15 
    16 </soap:Envelope>

四、WSDL(Web Services Description Language)

  • 网络服务描述语言是一种使用 XML 编写的文档。这种文档可描述某个 Web service, 例如服务的名称, 地址, 方法, 参数类型, 返回值类型等
  • Web服务的使用说明书
  • 每一个WebService都有一个对应的WSDL
  • WSDL地址组成 : 服务发布地址?wsdl
  • WSDL文档示例
     1 <message name="getTermRequest">
     2   <part name="term" type="xs:string"/>
     3 </message>
     4 
     5 <message name="getTermResponse">
     6   <part name="value" type="xs:string"/>
     7 </message>
     8 
     9 <portType name="glossaryTerms">
    10   <operation name="getTerm">
    11     <input message="getTermRequest"/>
    12     <output message="getTermResponse"/>
    13   </operation>
    14 </portType>

四、Apache CXF 框架

  • 主页: http://cxf.apache.org/

  • Apache CXF = Celtix + XFire,开始叫 Apache CeltiXfire,后来更名为 Apache CXF 了,以下简称为 CXF。CXF 继承了 Celtix 和 XFire 两大开源项目的精华,提供了对 JAX-WS 全面的支持,并且提供了多种 Binding 、DataBinding、Transport 以及各种 Format 的支持,并且可以根据实际项目的需要,采用代码优先(Code First)或者 WSDL 优先(WSDL First)来轻松地实现 Web Services 的发布和使用。Apache CXF已经是一个正式的Apache顶级项目。

1、CXF提供的服务分为两种方式

  • JAX-WS

    • 全称是 JavaTM API forRESTful Web Services

  • JAX-RS

    • 全称是 Java API for RESTful Web Services

  • 关于JAX-WS与JAX-RS两者是不同风格的SOA架构。前者以动词为中心,指定的是每次执行函数。而后者以名词为中心,每次执行的时候指的是资源

  • JAX-RS是JAVA EE6 引入的一个新技术。

  • 是一个Java 编程语言的应用程序接口,支持按照表述性状态转移(REST)架构风格创建Web服务。JAX-RS使用了Java SE5引入的Java标注来简化Web服务的客户端和服务端的开发和部署。

  • 简单来理解两种方式的区别

    • JAX-WS是基于SOAP协议传输XML数据

    • JAX-RS是基于HTTP协议传输XML数据或JSON数据

2、使用CXF开发WebService服务端(JAX-RS)

  • RESTful

    • 一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

  • RESTful的好处

    • 基于这种风格架构,软件编写可以更简洁

    • 基于HTTP协议, 支持多种消息格式,比如XML 、JSON

    • 更易于实现缓存机制

  • 创建Maven工程,类型为WAR

  • 引入坐标

    <!--cxf-rs的坐标 -->

 1 <dependency>
 2     <groupId>org.apache.cxf</groupId>
 3     <artifactId>cxf-rt-frontend-jaxrs</artifactId>
 4     <version>3.0.1</version>
 5 </dependency>
 6 <!-- 增强cxf-rs,可以处理json数据 -->
 7 <dependency>
 8     <groupId>org.apache.cxf</groupId>
 9     <artifactId>cxf-rt-rs-extension-providers</artifactId>
10     <version>3.0.1</version>
11 </dependency>
12 <!-- 上面的依赖必须依赖此包 -->
13 <dependency>
14     <groupId>org.codehaus.jettison</groupId>
15     <artifactId>jettison</artifactId>
16     <version>1.3.7</version>
17 </dependency>
18 <!-- spring坐标 -->
19 <dependency>
20     <groupId>org.springframework</groupId>
21     <artifactId>spring-context</artifactId>
22     <version>4.1.7.RELEASE</version>
23 </dependency>
24 <!--spring整合web开发 -->
25 <dependency>
26     <groupId>org.springframework</groupId>
27     <artifactId>spring-web</artifactId>
28     <version>4.1.7.RELEASE</version>
29 </dependency>
  • 创建实体类com.itheima.domain.User
 1 // 指定在序列化对象时,生成的根节点的名字
 2 @XmlRootElement(name = "user")
 3 public class User {
 4     private int id;
 5     private String name;
 6     private int age;
 7 ​
 8     public User() {
 9     }
10     public User(int id, String name, int age) {
11         super();
12         this.id = id;
13         this.name = name;
14         this.age = age;
15     }
16     public int getId() {
17         return id;
18     }
19     public void setId(int id) {
20         this.id = id;
21     }
22     public String getName() {
23         return name;
24     }
25     public void setName(String name) {
26         this.name = name;
27     }
28     public int getAge() {
29         return age;
30     }
31     public void setAge(int age) {
32         this.age = age;
33     }
34     @Override
35     public String toString() {
36         return "User [>;
37     }
38 }
  • 创建接口com.itheima.service.UserService

 1 public interface UserService {
 2     // URL = http://localhost:8080/rs_server/webservice/userService/user
 3     @POST
 4     @Path("/user")
 5     @Consumes({ "application/xml", "application/json" })
 6     public void saveUser(User user);
 7 ​
 8     // URL = http://localhost:8080/rs_server/webservice/userService/user?id=1
 9     @DELETE
10     @Path("/user")
11     @Consumes({ "application/xml" })
12     public void delUser(@QueryParam("id") int id);
13 ​
14     // URL = http://localhost:8080/rs_server/webservice/userService/user
15     @PUT
16     @Path("/user")
17     @Consumes({ "application/xml", "application/json" })
18     public void updateUser(User user);
19 ​
20     // URL = http://localhost:8080/rs_server/webservice/userService/user
21     @GET
22     @Path("/user")
23     @Produces({ "application/xml", "application/json" })
24     public List<User> findAllUsers();
25 ​
26     // URL = http://localhost:8080/rs_server/webservice/userService/user/1
27     @GET
28     @Path("/user/{id}")
29     @Consumes({ "application/xml" })
30     @Produces({ "application/xml", "application/json" })
31     public User findUserByID(@PathParam("id") int id);
32 }
  • 创建接口实现类
 1 public class UserServiceImpl implements UserService {
 2 
 3     @Override
 4     public void saveUser(User user) {
 5         System.out.println("用户保存成功:" + user);
 6     }
 7 ​
 8     @Override
 9     public void delUser(int id) {
10         System.out.println("ID为 " + id + " 的用户删除成功");
11     }
12 ​
13     @Override
14     public void updateUser(User user) {
15         System.out.println("用户更新成功:" + user);
16     }
17 ​
18     @Override
19     public List<User> findAllUsers() {
20         List<User> list = new ArrayList<>();
21         list.add(new User(1, "zhangsan", 11));
22         list.add(new User(2, "lisi", 22));
23         return list;
24     }
25 ​
26     @Override
27     public User findUserByID(int id) {
28         return new User(1, "zhangsan", 11);
29     }
30 }
  • 在web.xml中增加以下配置
 1 <!-- 指定Spring框架配置文件的位置 -->
 2 <context-param>
 3     <param-name>contextConfigLocation</param-name>
 4     <param-value>classpath:applicationContext.xml</param-value>
 5 </context-param>
 6 <!-- 配置Spring框架的监听器 -->
 7 <listener>
 8     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 9 </listener>
10 <!-- 配置CXF的Servlet -->
11 <servlet>
12     <servlet-name>cxf</servlet-name>
13     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
14 </servlet>
15 <!--指定Servlet的访问路径 -->
16 <servlet-mapping>
17     <servlet-name>cxf</servlet-name>
18     <url-pattern>/webservice/*</url-pattern>
19 </servlet-mapping>
  • 配置applicationContext.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <beans xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 5     xmlns:soap="http://cxf.apache.org/bindings/soap"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7               http://www.springframework.org/schema/beans/spring-beans.xsd
 8               http://www.springframework.org/schema/tx
 9                http://www.springframework.org/schema/tx/spring-tx.xsd
10               http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd ">
11     <!-- 注册服务提供者 -->
12     <bean  class="com.itheima.service.impl.UserServiceImpl"></bean>
13     <!--
14         发布Web服务
15         address : 请求地址
16     -->
17     <jaxrs:server address="/userService">
18         <jaxrs:serviceBeans>
19             <ref bean="userServiceImpl" />
20         </jaxrs:serviceBeans>
21         <!--
22             拦截请求信息,非必须
23             设置后,可以在控制台观察到请求信息
24         -->
25         <jaxrs:inInterceptors>
26             <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
27         </jaxrs:inInterceptors>
28         <!--
29             拦截响应信息,非必须
30             设置后,可以在控制台观察到响应信息
31         -->
32         <jaxrs:outInterceptors>
33             <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
34         </jaxrs:outInterceptors>
35     </jaxrs:server>
36 </beans>

3、使用CXF开发WebService客户端(JAX-RS)

  • 创建Maven工程,类型为JAR

  • 引入坐标
 1 <!-- cxf-rs的坐标 -->
 2 
 3 <dependency>
 4     <groupId>org.apache.cxf</groupId>
 5     <artifactId>cxf-rt-frontend-jaxrs</artifactId>
 6     <version>3.0.1</version>
 7 </dependency>
 8 <!-- cxf-rs客户端的坐标 -->
 9 <dependency>
10     <groupId>org.apache.cxf</groupId>
11     <artifactId>cxf-rt-rs-client</artifactId>
12     <version>3.0.1</version>
13 </dependency>
14 <!-- 增强cxf-rs,可以处理json数据 -->
15 <dependency>
16     <groupId>org.apache.cxf</groupId>
17     <artifactId>cxf-rt-rs-extension-providers</artifactId>
18     <version>3.0.1</version>
19 </dependency>
20 <!-- 上面的依赖必须依赖此包 -->
21 <dependency>
22     <groupId>org.codehaus.jettison</groupId>
23     <artifactId>jettison</artifactId>
24     <version>1.3.7</version>
25 </dependency>
26 </dependencies>
  • 将Server工程的实体类拷贝过来

  • 示例测试代码

 1 public class CXFTest { 
 2   ​// HTTP 405 Method Not Allowed : 请求方式错误,例如,服务端要求使用POST请求,客户端发起请求的时候,使用了PUT请求
 3   //保存
 4   ​@Test
 5   ​public void test1() {
 6     ​​WebClient// 服务器地址 : 端口号/项目名/
 7 ​​​​​        // web.xml中cxfServlet指定的地址/applicationContext.xml中指定的地址/类上Path指定的地址/方法上Path指定的地址
 8       ​​​​.create("http://localhost:8080/cxf_rs_server/webService/userService/user")// 指定请求的地址
 9     ​​​​  .post(new User(11, "张三", "123"));
10   ​}
11    //删除
12   ​@Test
13   ​public void test2() {
14     ​​WebClient
15       ​​​​.create("http://localhost:8080/cxf_rs_server/webService/userService/user")
16 ​​​​      .query("id", 100).delete();
17 ​  }
18  
19   //更新
20   ​@Test
21   ​public void test3() {
22     ​​WebClient
23 ​​​​      .create("http://localhost:8080/cxf_rs_server/webService/userService/user")
24 ​​​​      .put(new User(11, "张三", "123"));
25 ​  } 
26   
27    //查询所有
28   ​@Test
29   ​public void test4() {
30     ​​Collection<? extends User> collection = WebClient
31       ​​​​.create("http://localhost:8080/cxf_rs_server/webService/userService/user")
32       ​​​​.getCollection(User.class);
33     for (User user : collection) {
34         ​​​System.out.println(user);
35 ​​    }
36 ​  }
37  
38   //根据字段查询结果
39 ​  @Test
40 ​  public void test5() {
41     ​​User user = WebClient
42     ​​​​  .create("http://localhost:8080/cxf_rs_server/webService/userService/user")
43 ​​​​      .query("id", 11).get(User.class);
44  
45     ​​System.out.println(user);
46   ​}
47  
48   ​@Test
49   ​public void test6() {
50 ​​    User user = WebClient
51       ​​​​.create("http://localhost:8080/cxf_rs_server/webService/userService/user/" + 22 + "/icon")
52       ​​​​.get(User.class);
53  
54     ​​System.out.println(user);
55 ​  }
56 ​
57   ​@Test
58   ​public void test7() {
59     ​​WebClient
60 ​​​​      .create("http://localhost:8080/cxf_rs_server/webService/userService/user")// 指定请求的地址
61       ​​​​.type(MediaType.APPLICATION_JSON)// 指定本客户端传递给服务器的数据格式
62       ​​​​.accept(MediaType.APPLICATION_JSON)//指定服务器传递回来的数据格式,本客户端能处理的数据格式
63 ​​​​      .post(new User(11, "张三", "123"));
64   ​}
65 }

4、RESTFul常用注解

4.1 路径相关

  • @Path : 设置访问路径. 可以用在方法或类上面

4.2 参数类型相关

  • @Consumers: 定义方法参数类型,常用值为 : "application/xml", "application/json"

  • @Producers: 定义方法返回值类型,常用值为 : "application/xml", "application/json"

4.3 参数相关

  • @QueryParam : 查询参数. 客户端传参:url?id=10

  • @PathParam : 路径参数. 客户端传参:url/10

4.4 操作类型相关

  • @GET: 查询操作

  • @POST: 添加操作

  • @DELETE : 删除操作

  • @PUT: 修改操作