cxf入门和练习

雨燕双飞 提交于 2020-01-09 00:59:27

一、什么是cxf

Apache CXF=Celtix+Xfire
支持多种协议:
1)SOAP1.1,1.2
2)HTTP
3)可以与spring进行快速无缝整合
4)灵活部署:可以运行有tomcat,JBoss,Jetty(内置),IBMWS上面。

二、环境搭建

1)JAVA_HOME,需要jdk的支持
2)CXF_HOME

三、实现cxf第一个示例

1、创建java项目
2、引入所有依赖的包
3、创建服务类:
用两个不同的类发布应用:
ServerFactoryBean(不需要使用@WebService),但是生产的文档不规范,不建议使用;
JaxWsServerFactoryBean(建议使用此类,需要使用@WebService),生产的文档规范,可以发布SOAP1.1,SOAP1.2的协议,当cxf的服务类中没有方法也可以发布,不报错。如果使用SOAP1.2需要使用@binType注解指定
当使用SOAP1.2时wsimport命令失效,需要使用cxf的wsdl2java.
建议:发布服务的时候使用SOAP1.2,客户端调用的时候使用wsdl2java.

@WebService
@BindingType(value=javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING)
public class HelloService {
	
	public static void main(String[] args) {
		//创建服务工厂对象
		//ServerFactoryBean sfb = new ServerFactoryBean();
JaxWsServerFactoryBean sfb = new JaxWsServerFactoryBean ();
		//设置服务地址
		sfb.setAddress("http://127.0.0.1:7777/hello");
		//设置服务类
		sfb.setServiceClass(HelloService.class);
		//设置服务对象的实例
		sfb.setServiceBean(new HelloService());
		//发布服务
		sfb.create();
	}
	public String sayHello(String name){
		return name+ " hello";
	}
}

4、通过wsimport(SOAP1.1)生成客户端代码
5、调用WebService

四、wsdl2java使用

在cxf中,也提供了一个用于一生成客户端调用代码的工具。它的功能就如同wsimport一样。
cxf可以生成一堆客户端调用的代码。既可以生成soap1.1,也可以生成soap1.2.
此工具位于cxf_home/bin目录下。参数与wsimport有所不同。
1)-d 参数,指定代码生成的目录。
2)-p 参数,指定生成的新的包结构。
在命令行执行:

wsdl2java –d . http://127.0.0.1:6666/helloworld?wsdl

五、使用JaxWsServerFactoryBean调用接口服务类

1、创建服务接口

@WebService//注意注解加在接口上
public interface HI {

	public String sayHi(String name);
}

2、创建接口实现类

public class HIImpl implements HI {

	@Override
	public String sayHi(String name) {
		// TODO Auto-generated method stub
		return name + " hello";
	}
}

3、创建发布服务类

public static void main(String[] args) {
		JaxWsServerFactoryBean jf = new JaxWsServerFactoryBean();
		jf.setAddress("http://127.0.0.1:5555/hi");
		jf.setServiceClass(HI.class);
		jf.setServiceBean(new HIImpl());
		jf.create();
	}

4、生成客户端代码

wsdl2java -d . http://127.0.0.1:5555/hi?wsdl

5、调用客户端

public class Client {
	public static void main(String[] args) {
		HIService hs = new HIService();
		HI serviceClass = hs.getHIPort();
		System.out.println(serviceClass.sayHi("张三"));
	}
}

六、拦截输入输出消息

LoggingInInterceptor – 信息输入时的拦截器 –请求
LoggingOutInterceptor –信息输出时的拦截器-响应

public class InterServer {
	
	public static void main(String[] args) {
		JaxWsServerFactoryBean jf = new JaxWsServerFactoryBean();
		jf.getInInterceptors().add(new LoggingInInterceptor());
		jf.getOutInterceptors().add(new LoggingOutInterceptor());
		jf.setAddress("http://127.0.0.1:5555/hi");
		jf.setServiceClass(HI.class);
		jf.setServiceBean(new HIImpl());
		jf.create();
	}

}

七、在web项目中创建类的cxf服务

1、创建web项目
2、导入所有的包
3.创建服务类,必须指定注解@WebService
4、配置web.xml

<!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>
    <servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>

5、创建cxf的核心配置文件cxf-servlet.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"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd
            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
	<!-- 引入CXF Bean定义如下,早期的版本中使用 -->
	<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="hello" address="/hello" implementor="com.rl.cxf.web.server.HelloService">
		<jaxws:outInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
		</jaxws:outInterceptors>
		<jaxws:inInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
		</jaxws:inInterceptors>
	</jaxws:endpoint>
	
</beans>

注意:可以修改cxf-servlet.xml的位置和文件名
(1)第一种方式

<!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>
    <servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        
        <init-param>
			<param-name>config-location</param-name>
			<param-value>classpath:cxf.xml</param-value>
		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

(2)第二种方式

<!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>
	<listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:cxf.xml</param-value>
    </context-param>
     <servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

八、在web项目中创建接口的cxf服务 直接配置cxf-servlet.xml

<jaxws:server id="bye" address="/bye" serviceClass="com.rl.cxf.web.inter.ByeInter">
		<jaxws:serviceBean>
			<bean class="com.rl.cxf.web.inter.ByeInterImpl"></bean>
		</jaxws:serviceBean>
		<jaxws:outInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
		</jaxws:outInterceptors>
		<jaxws:inInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
		</jaxws:inInterceptors>
	</jaxws:server>

九、使用jQuery调用cxf
(1)简单的调用

$(function(){
		$("#mybutton").click(function(){
			var data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://server.web.cxf.rl.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
				  +'<soapenv:Body>'
				  +'<q0:sayHello>'
				  +'   <arg0>sss</arg0>'
				  +' </q0:sayHello>'
				  +'</soapenv:Body>'
				  +'</soapenv:Envelope>';
				  
				$.ajax({
					url:'http://localhost:8080/cxf-web-server/services/hello',
					type:'post',
					dataType:'xml',
					contentType:'text/xml;charset=UTF-8',
					data:data,
					success:function(responseText){
						alert($(responseText).find('return').text());
					},
					error:function(){
						alert("error");
					}
				})
		})
	})

(2)练习–实现添加和查询人

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<script type="text/javascript">

	$(function(){
		
		//保存用户
		$("#save").click(function(){
			var name = $("#name").val();
			var age = $("#age").val();
			var gender = $("#gender").val();
			$.ajax({
				url:"http://localhost:8080/cxf_web_server/services/person",
				type:"POST",
				dataType:"xml",
				contentType:"text/xml;charset=UTF-8",
				data:'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://server.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
				+'<soapenv:Body>'
				+'<q0:addPerson>'
				+'<arg0>'
				+'<age>'+age+'</age> '
				+'<gender>'+gender+'</gender> '
				+'<name>'+name+'</name> '
				+'</arg0>'
				+'</q0:addPerson>'
				+'</soapenv:Body>'
				+'</soapenv:Envelope>',
				success:function(data){
					alert('保存成功');
				},
				error:function(){
					alert("system error");
				}
			});
		});
		
		//查询用户
		$("#query").click(function(){
			
			$.ajax({
				url:"http://localhost:8080/cxf_web_server/services/person",
				type:"POST",
				dataType:"xml",
				contentType:"text/xml;charset=UTF-8",
				data:'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://server.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
				+' <soapenv:Body>'
				+' <q0:queryPersonAll /> '
				+' </soapenv:Body>'
				+' </soapenv:Envelope>',
				success:function(data){
					var doc = $(data).find('return');
					$("#mydiv").empty();
					var result = '';
					doc.each(function(){
						var name = $(this).find('name').text();
						var age = $(this).find('age').text();
						var gender = $(this).find('gender').text();
						
						result = result + name + "   "+ age + "   " + gender + "<br>";
						
					});
					$("#mydiv").append(result);
					
				},
				error:function(){
					alert("system error");
				}
			});
		});
	});
	
</script>
</head>
<body>

姓名:<input id="name" type="text"><br>
年龄:<input id="age" type="text"><br>
性别:<input id="gender" type="text"><br>
<input id="save" type="button" value="保存"><input id="query" type="button" value="查询"><br>
<div id="mydiv" style="width:300px;height:300px; border:1px solid;">

</div>
</body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!