Apache CXF开发Web Service 开发Web Service之Kick Start

2023-10-11 16:48

本文主要是介绍Apache CXF开发Web Service 开发Web Service之Kick Start,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Web Service看起来很神秘,不过你使用了Apache CXF之后,“啊~~~,Web Service是这么简单”。本节将介绍Apache CXF是基于JAX-WS创建Web Service。有兴趣的话请看《JAX-WS Specificantion》

 

JAX-WS提供了两种方式来创建Web Service:Code-First和Contract-First。本节使用Code-First的方式:先创建Java类然后基于Java类生成Web Service组件。任务的第一步就是来创建服务器端组件。想更深一步了解请看:《代码优先(Code-First)和契约优先(Contract-First)的比较》。

 

创建服务器端组件,我们需要执行如下步骤:

创建Service Endpoint Interface (SEI),也就是JAVA中的Interface,定义Web Service使用的业务方法。

创建SEI的实现类,声明这是一个Web Service。

 

 

 

创建Service Endpoint Interface (SEI)

 

package demo.order;

 

import javax.jws.WebService;

 

@WebService

public interface OrderProcess {

@WebMethod

    String processOrder(Order order);

}

 

正如你看到的,我们创建了名叫processOrder 的Service Endpoint Interface (SEI)。这个SEI就像其他Java Interface一样。定义了接口方法:processOrder。这个方法需要输入Java Bean (Order) 作为参数,并返回字符型的order ID。processOrder的目的是来处理顾客下订单并返回唯一的订单ID。

 

突出显示的地方@WebService Annotation。它强调这不是普通的Interface,而是Web Service Interface,也就是SEI,用于向客户端外暴露接口调用方法。

 

JAX-WS规范中注解库包含了@WebService Annotation。JAX-WS规范通过注解库的形式将POJO对外暴露为Web Service,并定义了WSDL和JAVA类之间Web Serive的映射关系。当然javax.jws.WebService还有很多细节内容,这里不再深入讨论。

 

javax.jws.@WebMethod注解是可选的内容,用来制定Web Service的操作。@WebMethod Annotation说明了方法名,还有action 元素,作为自定义操作的name属性来和WSDL文档的SOAP action元素对应。

 

 

 

创建Java Bean Order

 

package demo.order;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Order")

public class Order {

 

         private String customerID;

         private String itemID;

         private Integer qty;

         private Double price;

        

         // Contructor

         public Order() {

         }

 

         public String getCustomerID() {

                   return customerID;

         }

 

         public void setCustomerID(String customerID) {

                   this.customerID = customerID;

         }

 

         public String getItemID() {

                   return itemID;

         }

 

         public void setItemID(String itemID) {

                   this.itemID = itemID;

         }

 

         public Integer getQty() {

                   return qty;

         }

 

         public void setQty(Integer qty) {

                   this.qty = qty;

         }

 

         public Double getPrice() {

                   return price;

         }

 

         public void setPrice(Double price) {

                   this.price = price;

         }

 

}

 

可以清楚的看到,对Order类添加@XmlRootElement注解。Java Architecture for XML Binding (JAXB) 规范中注解库包含了@XmlRootElement。JAXB提供了快速而简便的方法将XML模式绑定到Java表示。JAXB隐含了SOAP消息和Java代码的转换细节,节XML和SOAP的解析,开发者不用知道这一过程。CXF默认使用JAXB作为数据绑定工具。

 

@XmlRootElement指定Order类作为XML的根节点。Order对象的属性会默认的注解为@XmlElement。@XmlElement用来定义XML的子节点。@XmlRootElement和@XmlElement让你自定义XML的命名空间和XML元素。如果没有自定义,JAXB会默认使用相同的名称的属性作为XML子节点。CXF处理JAVA对象到XML的映射关系。

 

 

 

创建Serivce Implementation Class

 

package demo.order;

 

import javax.jws.WebService;

 

@WebService

public class OrderProcessImpl implements OrderProcess {

 

         public String processOrder(Order order) {

                   String orderID = validate(order);

                   System.out.println("Processed order..." + orderID);

        return orderID;

    }

 

         /**

          * Validates the order and returns the order ID

         **/

         private String validate(Order order) {

                   String custID = order.getCustomerID();

                   String itemID = order.getItemID();

                   int qty = order.getQty();

                   double price = order.getPrice();

 

                   if (custID != null && itemID != null && !custID.equals("") &&

                                     !itemID.equals("") && qty > 0 && price > 0.0) {

                            return "ORD1234";

                   }

                   return null;

         }

 

}

 

实现类很简单。也提供了@WebService注解。OrderProcessImpl实现OrderProcess (SEI) 中的processOrder方法。processOrder方法通过validate方法来验证订单是否有效。

 

 

 

基于Spring服务端

 

CXF官方文档(http://cxf.apache.org/docs/why-cxf.html)中写道:

 

“Spring is a first class citizen with Apache CXF. CXF supports the Spring 2.0 XML syntax, making it trivial to declare endpoints which are backed by Spring and inject clients into your application.”

 

CXF使用基于Spring配置文档来发布Web service endpoints。正是这一点促使CXF成为Web Service框架里的首选。这里将利用基于Spring配置位置来创建服务端。配置文档为bean.xml。

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xmlns:jaxws="http://cxf.apache.org/jaxws"

         xsi:schemaLocation="

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

 

         <import resource="classpath:META-INF/cxf/cxf.xml" />

         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />

         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

 

         <jaxws:endpoint

           id="orderProcess"

           implementor="demo.order.OrderProcessImpl"

           address="/OrderProcess" />

          

</beans>

 

首先定义了文档中使用的命名空间<jaxws>,然后使用<import>导入cxf.xml, cxf-extension-soap.xml和cxf-servlet.xml。这些都是基于Spring的配置文档,定义了CXF的核心组件,提供CXF的运行环境,加载必要基础对象例如:WSDL manager, conduit manager, destination factory manager等。

 

<jaxws:endpoint>节点指定OrderProcess作为JAX-WS的endpoint。定义了如下三种属性:

Id - 指定Bean的唯一标示符。

Implementor - 指定Web Service的实现类。

Address – 指定URL访问Web Service的地址。这个是相对地址,具体链接和发布的Web容器相关。

 

<jaxws:endpoint>定义了CXF内置使用JAX-WS frontend来发布Web Service。节点的内容简短、方便,开发者不需要额外的编写其他内容来发布Web Service。

 

 

 

创建基于Spring的客户端

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xmlns:jaxws="http://cxf.apache.org/jaxws"

         xsi:schemaLocation="

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

 

    <jaxws:client id="orderClient" serviceClass="demo.order.OrderProcess" address="http://localhost:8080/orderapp/OrderProcess" >

    </jaxws:client>

 

</beans>

 

在client-beans.xml中<jaxws:client>指定了客户端使用JAX-WS frontend。定义了如下三种属性:

Id - 指定Bean的唯一标示符。

serviceClass - 指定Web Service的SEI。

Address – 指定URL访问Web Service的地址。这个绝对地址地址,指向Web Service的访问路径。

 

 

 

创建客户端代码

 

package demo.order.client;

 

 

import demo.order.OrderProcess;

import demo.order.Order;

 

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

 

public final class Client {

 

    public Client() {

    }

 

    public static void main(String args[]) throws Exception {

         ClassPathXmlApplicationContext context

            = new ClassPathXmlApplicationContext(new String[] {"client-beans.xml"});

 

        OrderProcess client = (OrderProcess) context.getBean("orderClient");

                   Order order = new Order();

                   order.setCustomerID("C001");

                   order.setItemID("I001");

                   order.setQty(100);

                   order.setPrice(200.00);

 

        String orderID = client.processOrder(order);

        String message = (orderID == null) ? "Order not approved" : "Order approved; order ID is " + orderID;

                   System.out.println(message);

           

    }

}

 

在代码中使用ClassPathXmlApplicationContext加载client-beans.xml配置文件。

 

 

 

配置Web容器

 

<!DOCTYPE web-app PUBLIC

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

 "http://java.sun.com/dtd/web-app_2_3.dtd" >

 

<web-app>

    <display-name>Archetype Created Web Application</display-name>

  

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>WEB-INF/beans.xml</param-value>

    </context-param>

 

    <listener>

        <listener-class>

                            org.springframework.web.context.ContextLoaderListener

        </listener-class>

    </listener>

 

    <servlet>

        <servlet-name>CXFServlet</servlet-name>

        <display-name>CXF Servlet</display-name>

        <servlet-class>

                            org.apache.cxf.transport.servlet.CXFServlet

        </servlet-class>

        <load-on-startup>1</load-on-startup>

    </servlet>

 

    <servlet-mapping>

        <servlet-name>CXFServlet</servlet-name>

        <url-pattern>/*</url-pattern>

    </servlet-mapping>

</web-app>

 

通过web.xml将Spring和CXF整合起来。org.apache.cxf.transport.servlet.CXFServlet初始化了CXF运行环境。org.springframework.web.context.ContextLoaderListener加载了beans.xml的配置。

 

 

 

运行Web Service

 

这里使用Maven来作为构建工具。如果想立刻看到效果请使用NetBean,内置了Maven。如果使用eclipse则需要添加m2eclipse插件,参见Eclipse 的 Maven 插件 m2eclipse。

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.dcb.cxfbook.ch02</groupId>

    <artifactId>orderapp</artifactId>

    <packaging>war</packaging>

    <version>1.0-SNAPSHOT</version>

    <name>orderapp Maven Webapp</name>

    <url>http://maven.apache.org</url>

    <properties>

                   <!-- Version of CXF. Change this to latets version for building against latest CXF distribution -->

        <cxf.version>2.2.3</cxf.version>

    </properties>

    <dependencies>

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>3.8.1</version>

            <scope>test</scope>

        </dependency>

        <dependency>

                       <!-- Apache JAX-WS CXF Dependency for WAR and JAX-WS Client-->

            <groupId>org.apache.cxf</groupId>

            <artifactId>cxf-rt-frontend-jaxws</artifactId>

            <version>${cxf.version}</version>

        </dependency>

        <dependency>

                       <!-- Apache JAX-WS CXF Dependency for JAX-WS Client-->

            <groupId>org.apache.cxf</groupId>

            <artifactId>cxf-rt-transports-http</artifactId>

            <version>${cxf.version}</version>

        </dependency>

    </dependencies>

    <build>

        <finalName>orderapp</finalName>

        <plugins>

            <plugin>

                                     <!-- Plugin for compiling Java code -->

                <artifactId>maven-compiler-plugin</artifactId>

                <configuration>

                                        <!-- Java version for compiling the source code-->

                    <source>1.5</source>

                    <target>1.5</target>

                </configuration>

            </plugin>

            <plugin>

                <groupId>org.mortbay.jetty</groupId>

                <artifactId>maven-jetty-plugin</artifactId>

                <version>6.1.19</version>

            </plugin>

        </plugins>

    </build>

    <profiles>

        <profile>

            <id>client</id>

            <build>

                <defaultGoal>test</defaultGoal>

                <plugins>

                    <plugin>

                        <groupId>org.codehaus.mojo</groupId>

                        <artifactId>exec-maven-plugin</artifactId>

                        <executions>

                            <execution>

                                <phase>test</phase>

                                <goals>

                                    <goal>java</goal>

                                </goals>

                                <configuration>

                                    <mainClass>demo.order.client.Client</mainClass>

                                </configuration>

                            </execution>

                        </executions>

                    </plugin>

                </plugins>

            </build>

        </profile>

    </profiles>

</project>

 

pom.xml中,添加cxf-rt-frontend-jaxws和cxf-rt-transports-http依赖,maven会自动加载相关的jar包,包括CXF, Spring, common, JABX。在Build. Plugins. Plugin节点添加maven-jetty-plugin作为Web容器,方便测试。在profiles. Profile. Build. Plugins. Plugin节点添加exec-maven-plugin提供命令行运行demo.order.client.Client。

 

cd orderapp

#启动jetty

mvn jett:run

#执行client

mvn test -Pclient

 

执行client可以直接在IDE (Netbean or Eclipse)中运行。

 

 

 

 

名词解释:

 

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

Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。

JCP(Java Community Process) 是一个开放的国际组织,主要由Java开发者以及被授权者组成,职能是发展和更新。

CXF frontends are programming APIs that can be used to develop and publish web services. CXF supports two types of frontends, JAX-WS and simple frontend.

JAX-WS规范是一组XML web services的JAVA API,JAX-WS允许开发者可以选择RPC-oriented或者message-oriented 来实现自己的web services。

java.lang.annotation,接口 Annotation。对于Annotation,是Java5的新特性,JDK5引入了Metedata(元数据)很容易的就能够调用Annotations.Annotations提供一些本来不属于程序的数据,比如:一段代码的作者或者告诉编译器禁止一些特殊的错误。An annotation 对代码的执行没有什么影响。Annotations使用@annotation的形势应用于代码:类(class),属性(field),方法(method)等等。一个Annotation出现在上面提到的开始位置,而且一般只有一行,也可以包含有任意的参数。

Java annotation: An annotation, in the Java computer programming language, is a form of syntactic metadata that can be added to Java source code.[1] Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.[2] It is possible to create meta-annotations out of the existing ones in Java, which makes this concept more sophisticated than in other languages like C#

POJO(Plain Old Java Objects)简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称。

Web Services Description Language的缩写,是一个用来描述Web服务和说明如何与Web服务通信的XML语言。为用户提供详细的接口说明书。

JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。从另一方面来讲,JAXB提供了快速而简便的方法将XML模式绑定到Java表示,从而使得Java开发者在Java应用程序中能方便地结合XML数据和处理函数。

SOAP:简单对象访问协议,简单对象访问协议(SOAP)是一种轻量的、简单的、基于 XML 的协议,它被设计成在 WEB 上交换结构化的和固化的信息。 SOAP 可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议( HTTP),简单邮件传输协议(SMTP),多用途网际邮件扩充协议(MIME)。它还支持从消息系统到远程过程调用(RPC)等大量的应用程序。

 

 

 

 

参考内容:

 

http://baike.baidu.com/view/2742297.htm CXF百科

http://baike.baidu.com/view/148425.htm JCP百科

http://baike.baidu.com/view/1865210.htm JAX-WS百科

http://baike.baidu.com/view/612195.htm Annotation百科

http://en.wikipedia.org/wiki/Java_annotation JAVA Annotation wiki百科

http://baike.baidu.com/view/183175.htm POJO百科

http://baike.baidu.com/view/160660.htm WSDL百科

http://baike.baidu.com/view/725509.htm JAXB百科

http://baike.baidu.com/view/60663.htm SOAP百科

http://www.jcp.org/en/home/index

http://jcp.org/aboutJava/communityprocess/final/jsr224/index.html

PacktPub.Apache.CXF.Web.Service.Development.Dec.2009 第三章

http://book.51cto.com/art/200911/163796.htm

http://cxf.apache.org/docs/why-cxf.html

http://www.oschina.net/p/m2eclipse

这篇关于Apache CXF开发Web Service 开发Web Service之Kick Start的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/189442

相关文章

基于Python开发PDF转Doc格式小程序

《基于Python开发PDF转Doc格式小程序》这篇文章主要为大家详细介绍了如何基于Python开发PDF转Doc格式小程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用python实现PDF转Doc格式小程序以下是一个使用Python实现PDF转DOC格式的GUI程序,采用T

使用Python开发一个图像标注与OCR识别工具

《使用Python开发一个图像标注与OCR识别工具》:本文主要介绍一个使用Python开发的工具,允许用户在图像上进行矩形标注,使用OCR对标注区域进行文本识别,并将结果保存为Excel文件,感兴... 目录项目简介1. 图像加载与显示2. 矩形标注3. OCR识别4. 标注的保存与加载5. 裁剪与重置图像

使用Apache POI在Java中实现Excel单元格的合并

《使用ApachePOI在Java中实现Excel单元格的合并》在日常工作中,Excel是一个不可或缺的工具,尤其是在处理大量数据时,本文将介绍如何使用ApachePOI库在Java中实现Excel... 目录工具类介绍工具类代码调用示例依赖配置总结在日常工作中,Excel 是一个不可或缺的工http://

web网络安全之跨站脚本攻击(XSS)详解

《web网络安全之跨站脚本攻击(XSS)详解》:本文主要介绍web网络安全之跨站脚本攻击(XSS)的相关资料,跨站脚本攻击XSS是一种常见的Web安全漏洞,攻击者通过注入恶意脚本诱使用户执行,可能... 目录前言XSS 的类型1. 存储型 XSS(Stored XSS)示例:危害:2. 反射型 XSS(Re

Apache伪静态(Rewrite).htaccess文件详解与配置技巧

《Apache伪静态(Rewrite).htaccess文件详解与配置技巧》Apache伪静态(Rewrite).htaccess是一个纯文本文件,它里面存放着Apache服务器配置相关的指令,主要的... 一、.htAccess的基本作用.htaccess是一个纯文本文件,它里面存放着Apache服务器

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干