前言

自3月份到一家快递公司之后,就极少有时间来写博客了,进去的第一个周末就加班。做公司的开放平台,协助一个小伙伴写WebService接口,用的就是CXF。正好这个东西曾经使用过。如今快7月了,曾经写的东西。还木有写完,今天继续。将曾经未写完的东西。写完整。

准备工作

这次的例子,都是在曾经的基础上写的。主要贴出基本的代码。服务端和client都与Spring集成。使用了拦截器、Map数据类型等

服务端

共计写了四个服务。第一个主要说明服务端有多种公布方式,第二和第三实现类是同样的。差别在于第三个有拦截器,第四个包含拦截器和Map的数据类型,这些配置文件的凝视中也有。

配置文件内容例如以下:
<?

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-3.0.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-servlet.xml"/> --> <!-- 服务一。无client -->
<!-- 多种公布方式都能够
<bean id="noInterfaceServiceImpl"
class="com.wds.cxf.spring.server.impl.NoInterfaceServiceImpl"/>
<jaxws:endpoint address="/noInterfaceService"
implementor="#noInterfaceServiceImpl"
></jaxws:endpoint>
-->
<jaxws:endpoint
id="noInterfaceService" address="/noInterfaceService"
implementor="com.wds.cxf.spring.server.impl.NoInterfaceServiceImpl"
></jaxws:endpoint> <!-- 服务2:有client,不带拦截器 -->
<jaxws:server address="/userService2">
<jaxws:serviceBean>
<bean class="com.wds.cxf.spring.server.impl.UserServiceImpl"></bean>
</jaxws:serviceBean>
</jaxws:server> <!-- 服务3:有client。带拦截器 。与服务2是同样的代码。差别之处就是这个服务有拦截器-->
<jaxws:server address="/userService" serviceClass="com.wds.cxf.spring.server.IUserService">
<jaxws:serviceBean>
<bean class="com.wds.cxf.spring.server.impl.UserServiceImpl"></bean>
</jaxws:serviceBean>
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
<bean class="com.wds.cxf.spring.server.interceptor.HeaderHandlerInterceptor"></bean>
</jaxws:inInterceptors> <jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
</jaxws:outInterceptors>
</jaxws:server> <!-- 服务4:有拦截器,Map类型的数据结构 -->
<jaxws:server address="/SecurityService" serviceClass="com.wds.cxf.spring.server.ISecurityService">
<jaxws:serviceBean>
<bean class="com.wds.cxf.spring.server.impl.SecurityServiceImpl"></bean>
</jaxws:serviceBean>
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
<bean class="com.wds.cxf.spring.server.interceptor.HeaderHandlerInterceptor"></bean>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
</jaxws:outInterceptors>
</jaxws:server>
</beans>

第一个服务的类:

package com.wds.cxf.spring.server.impl;

import javax.jws.WebService;

@WebService
public class NoInterfaceServiceImpl { public String test(){
return "Hello, this is test method";
}
}

第二个和第三个服务的接口及实现类

package com.wds.cxf.spring.server;

import java.util.List;

import javax.jws.WebService;

@WebService
public interface IUserService {
public List<String> getUserName();
} 实现类
package com.wds.cxf.spring.server.impl; import java.util.ArrayList;
import java.util.List; import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding; import com.wds.cxf.spring.server.IUserService; @WebService(endpointInterface="com.wds.cxf.spring.server.IUserService",serviceName="UserService")
@BindingType(value=SOAPBinding.SOAP12HTTP_BINDING)
public class UserServiceImpl implements IUserService { @Override
public List<String> getUserName() {
List<String> userNameList = new ArrayList<String>(); String userName = "firstName";
userNameList.add(userName);
userName = "secondName";
userNameList.add(userName);
userName = "thirdName";
userNameList.add(userName); return userNameList;
} }

第四个服务

package com.wds.cxf.spring.server;

import java.util.List;
import java.util.Map; import javax.jws.WebService;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.wds.cxf.spring.server.adapter.MappingUser; @WebService
public interface ISecurityService {
@XmlJavaTypeAdapter(value=MappingUser.class)
public Map<String, List<User>> getAuthority();
} 实现类
package com.wds.cxf.spring.server.impl; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.wds.cxf.spring.server.ISecurityService;
import com.wds.cxf.spring.server.User; public class SecurityServiceImpl implements ISecurityService { @Override
public Map<String, List<User>> getAuthority() {
Map<String, List<User>> result = new HashMap<String, List<User>>();
User u = null;
List<User> users = new ArrayList<User>(10);
String key = "seriail1";
for (int i = 0; i < 10; i++) {
u = new User("name" + i, "code--" + i);
users.add(u);
}
result.put(key, users); users = new ArrayList<User>(10);
key = "seriail2";
for (int i = 20; i < 30; i++) {
u = new User("name" + i, "code--" + i);
users.add(u);
}
result.put(key, users); return result;
} }

类型转换的适配类两个

package com.wds.cxf.spring.server.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import javax.xml.bind.annotation.adapters.XmlAdapter; import com.wds.cxf.spring.server.User; public class MappingUser extends XmlAdapter<MappingUserValue, Map<String, List<User>>>{ @Override
public Map<String, List<User>> unmarshal(MappingUserValue src)
throws Exception {
Map<String, List<User>> target = new HashMap<String, List<User>>();
for (MappingUserValue.Entry entry : src.getEntries()) {
target.put(entry.getKey(), entry.getValue());
}
return target;
} @Override
public MappingUserValue marshal(Map<String, List<User>> src) throws Exception {
MappingUserValue result = new MappingUserValue();
MappingUserValue.Entry e = null;
for (Entry<String, List<User>> entry : src.entrySet()) {
e = new MappingUserValue.Entry();
e.setKey(entry.getKey());
e.setValue(entry.getValue());
result.getEntries().add(e);
}
return result;
} }


package com.wds.cxf.spring.server.adapter;

import java.util.ArrayList;
import java.util.List; import com.wds.cxf.spring.server.User; public class MappingUserValue {
private List<Entry> entries = new ArrayList<MappingUserValue.Entry>(); public List<Entry> getEntries() {
return entries;
} public void setEntries(List<Entry> entries) {
this.entries = entries;
} public static class Entry {
private String key;
private List<User> value; public List<User> getValue() {
return value;
} public void setValue(List<User> value) {
this.value = value;
} public String getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} } }

拦截器

package com.wds.cxf.spring.server.interceptor;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList; public class HeaderHandlerInterceptor extends AbstractPhaseInterceptor<Message> { public HeaderHandlerInterceptor(String phase) {
super(Phase.PRE_INVOKE);
} public HeaderHandlerInterceptor() {
this(null);
} @Override
public void handleMessage(Message message) throws Fault {
SoapMessage msg = (SoapMessage)message;
List<Header> headers = msg.getHeaders(); if(headers == null || headers.size() < 1){
throw new Fault(new IllegalArgumentException("There have no header node!"));
} Header firstHeader = headers.get(0); for (Header header : headers) {
QName qName = header.getName();
System.out.println(qName);
} Element element = (Element)firstHeader.getObject(); NodeList usernameNode = element.getElementsByTagName("username");
NodeList passwordNode = element.getElementsByTagName("password"); if(usernameNode == null || usernameNode.getLength() != 1){
throw new Fault(new IllegalArgumentException("not valid username"));
} if(passwordNode == null || passwordNode.getLength() != 1){
throw new Fault(new IllegalArgumentException("not valid password"));
} String userName = usernameNode.item(0).getTextContent();
String userPass = passwordNode.item(0).getTextContent(); if(!("admin".equals(userPass) && "admin".equals(userName))){
throw new Fault(new IllegalArgumentException("username or password is not valid"));
}
} }

至此,服务端的代码。所有齐了

client

client的代码是须要CXF的命令生成
<?

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-3.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml"/>
<!-- 第四个服务的客户端 -->
<jaxws:client
id="securityService"
address="http://localhost:8080/web/services/SecurityService"
serviceClass="com.wds.java.cxf.client.role.code.ISecurityService" >
<jaxws:outInterceptors>
<bean class="com.wds.java.cxf.interceptor.ClientHeaderInterceptor">
<constructor-arg index="0" value="admin" />
<constructor-arg index="1" value="admin" />
</bean>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxws:outInterceptors>
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</jaxws:inInterceptors>
</jaxws:client> <!-- 第三个服务的客户端 -->
<jaxws:client
id="userServiceOne"
address="http://localhost:8080/web/services/userService"
serviceClass="com.wds.java.cxf.client.user.code.IUserService" >
<jaxws:outInterceptors>
<bean class="com.wds.java.cxf.interceptor.ClientHeaderInterceptor">
<constructor-arg index="0" value="admin" />
<constructor-arg index="1" value="admin" />
</bean>
</jaxws:outInterceptors>
</jaxws:client> <!-- 第二个服务的客户端 -->
<jaxws:client
id="userServiceTwo"
address="http://localhost:8080/web/services/userService2"
serviceClass="com.wds.java.cxf.client.user.code.IUserService" /> </beans>

使用CXF的命令。生成客户端代码,加上面的配置。此外还须要一个拦截器,代码例如以下:

package com.wds.java.cxf.interceptor;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element; public class ClientHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage>{ private String username;
private String password; public ClientHeaderInterceptor(String phase) {
super(Phase.PREPARE_SEND);//在准备发送SOAP消息时,调用此拦截器
} public ClientHeaderInterceptor(String username, String password) {
this("");
this.username = username;
this.password = password;
} @Override
public void handleMessage(SoapMessage msg) throws Fault {
List<Header> headers = msg.getHeaders();
Document doc = DOMUtils.createDocument();
Element authEle = doc.createElement("header");
Element usernameEle = doc.createElement("username");
Element passwordEle = doc.createElement("password"); usernameEle.setTextContent(username);
passwordEle.setTextContent(password); authEle.appendChild(usernameEle); authEle.appendChild(passwordEle); Header header = new Header(new QName("authHeaer"), authEle); headers.add(header); authEle = doc.createElement("headerTwo");
usernameEle = doc.createElement("username");
passwordEle = doc.createElement("password"); usernameEle.setTextContent(username);
passwordEle.setTextContent(password); authEle.appendChild(usernameEle); authEle.appendChild(passwordEle); header = new Header(new QName("2authHeaer"), authEle); headers.add(header);
} }

測试类

package com.wds.java.cxf.client.user;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.wds.java.cxf.client.role.code.Entry;
import com.wds.java.cxf.client.role.code.ISecurityService;
import com.wds.java.cxf.client.role.code.MappingUserValue;
import com.wds.java.cxf.client.user.code.IUserService; public class Main { @SuppressWarnings("resource")
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/conf/cxf/spring-cxf-client.xml"); IUserService service = (IUserService) context.getBean("userServiceTwo");
List<String> userNames = service.getUserName(); service = (IUserService) context.getBean("userServiceOne");
List<String> userNamesOne = service.getUserName(); for (String string : userNames) {
System.out.println(string);
} for (String string : userNamesOne) {
System.out.println(string);
} ISecurityService securityService = (ISecurityService) context.getBean("securityService");
MappingUserValue userValue = securityService.getAuthority();
List<Entry> entries = userValue.getEntries();
for (Entry entry : entries) {
System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
}
} }

执行就可以







WebService-06-CXF与Spring集成的更多相关文章

  1. 使用CXF与Spring集成实现RESTFul WebService

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

  2. 使用Apache CXF和Spring集成创建Web Service(zz)

    使用Apache CXF和Spring集成创建Web Service 您的评价:       还行  收藏该经验       1.创建HelloWorld 接口类 查看源码 打印? 1 package ...

  3. 【WebService】WebService之CXF和Spring整合(六)

    前面介绍了WebService与CXF的使用,项目中我们经常用到Spring,这里介绍CXF与Spring整合 步骤 1.创建一个Maven Web项目,可以参照:[Maven]Eclipse 使用M ...

  4. 【WebService】——CXF整合Spring

    相关博客: [WebService]--入门实例 [WebService]--SOAP.WSDL和UDDI 前言: 之前的几篇博客基本上都是使用jdk来实现WebService的调用,没有使用任何框架 ...

  5. webservice的cxf和spring整合发布

    1.新建一个web项目 2.导入cxf相应的jar包,并部署到项目中 3.服务接口 package com.xiaostudy; /** * @desc 服务器接口 * @author xiaostu ...

  6. webservice的cxf和spring整合客户端开发

    1.新建一个java项目 2.导入cxf相关的jar包,并部署到项目中 3.用命令生成客户端使用说明文档 wsdl2java -p com.xiaostudy -d . http://127.0.0. ...

  7. WebService学习之三:spring+cxf整合

    步骤一:spring项目(java web项目)引入CXF jar包 步骤二:创建webservice服务器 1)创建一个服务接口 package com.buss.app.login; import ...

  8. CXF框架介绍及Spring集成

    1.CXF框架概念介绍 Apache CXF 是一个开源的 WebService 框架,CXF可以用来构建和开发 WebService,这些服务可以支持多种协议,比如:SOAP.POST/HTTP.H ...

  9. webservice第三篇【接口开发webservice、CXF框架使用、IDEA下使用webservice、小例子】

    实现接口的webservice 服务端 import javax.jws.WebService; /**面向接口的webservice发布方式 * * */ @WebService public in ...

  10. Spring集成CXF发布WebService并在客户端调用

    Spring集成CXF发布WebService 1.导入jar包 因为官方下载的包里面有其他版本的sprring包,全导入会产生版本冲突,所以去掉spring的部分,然后在项目根目录下新建了一个CXF ...

随机推荐

  1. 图像 - 创建 头像V1.0

    byte[] logo //处理群头像信息 //byte[] logoByte = Convert.FromBase64String(logo); ////1.0 System.IO.MemorySt ...

  2. Python学习之编写登陆接口(Day1,作业一)

    作业一:编写登陆接口 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定(下次登陆还是锁定) 知识点:while循环,for循环,文件操作,if判断,列表操作 思路: 1.登陆,三次登陆失败,锁定 ...

  3. SQL PLUS远程连接

    http://blog.csdn.net/wildin/article/details/5850252 这篇文章无敌了. Oracle sqlplus添加历史记录功能: http://www.cnbl ...

  4. 如何修改被编译后DLL文件

    原文 http://www.cnblogs.com/wujy/p/3275855.html 我们平时在工作中经常会遇到一些已经被编译后的DLL,而且更加麻烦是没有源代码可以进行修改,只能针对这个DLL ...

  5. CATALINA_BASE与CATALINA_HOME的区别(转)

    到底CATALINA_HOME和CATALINA_BASE有什么区别呢,之前因为都是小打小闹的在服务器上安装一个tomcat就得了,然后根据前人的配置,将CATALINA_HOME和CATALINA_ ...

  6. C语言的本质(7)——C语言运算符大全

    C语言的本质(7)--C语言运算符大全 C语言的结合方向 C语言中各运算符的结合性分为两种,即左结合性(自左至右)和右结合性(自右至左).例如算术运算符的结合性是自左至右,即先左后右.如有表达式 x- ...

  7. iOS5系统API和5个开源库的JSON解析速度测试

    iOS5系统API和5个开源库的JSON解析速度测试 iOS5新增了JSON解析的API,我们将其和其他五个开源的JSON解析库进行了解析速度的测试,下面是测试的结果和工程代码附件. 我们选择的测试对 ...

  8. 关于关注和取消关注的nodejs写法

    本例子的关注和取消关注,是通过ajax的方法实现的:nodejs后台写好api接口:响应前台的ajax 先看ajax的代码实现: // 用户关注标签 function subscribe(uid, t ...

  9. Little Zu Chongzhi's Triangles

    Little Zu Chongzhi's Triangles Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 512000/512000 ...

  10. Clojure 学习入门(19)—— 数组

    1.创建数组 1.1 从集合创建数组 into-array into-array (into-array aseq) (into-array type aseq) 演示样例: user=> (i ...