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

相关文章

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

Java Web指的是什么

Java Web指的是使用Java技术进行Web开发的一种方式。Java在Web开发领域有着广泛的应用,主要通过Java EE(Enterprise Edition)平台来实现。  主要特点和技术包括: 1. Servlets和JSP:     Servlets 是Java编写的服务器端程序,用于处理客户端请求和生成动态网页内容。     JSP(JavaServer Pages)

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

BUUCTF靶场[web][极客大挑战 2019]Http、[HCTF 2018]admin

目录   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 [web][HCTF 2018]admin 考点:弱密码字典爆破 四种方法:   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 访问环境 老规矩,我们先查看源代码

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧