1.关于CXF(摘自百度百科)
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顶级项目。
Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。
2.下载
http://cxf.apache.org/download.html
3.集成到eclipse
笔者下载的版本是2.7.7,进入apache-cxf-2.7.7/lib目录,将所需jar包复制到工程中,需要的jar包较多,如图:
4.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>PortalService</display-name> <!-- cfx webSerivice --> <servlet> <servlet-name>cxf</servlet-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <load-on-startup>1</load-on-startup> </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-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:soap="http://cxf.apache.org/bindings/soap" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <!-- ;服务接口 --> <jaxws:server id="jaxwsService" serviceClass="com.look.service.IService" address="/test"> <!-- address为服务发布二级地址 完整地址为 /项目发布名称/cfx拦截地址/address (cfx拦截地址在web.xml中url-pattern标签中配置) --> <jaxws:serviceBean> <!--服务实现类 --> <bean class="com.look.service.IServiceImpl" /> </jaxws:serviceBean> </jaxws:server> </beans>
6.IService.java
package com.look.service; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import com.protal.model.RequestCondition; @WebService public interface IService { @WebMethod String test(@WebParam RequestCondition requestCondition); }网上的例子多是String类型,这里使用了自定义的Java类型,RequestCondition类的代码这里不贴出了,读者可自行建立该bean,添加属性age并添加相应的set、get方法
7.IServiceImpl.java
package com.look.service; import com.protal.model.RequestCondition; public class IServiceImpl implements IService { @Override public String test(RequestCondition requestCondition) { return “年龄是:”+requestCondition.getAge(); } }
8.部署并测试
将项目部署到web服务器,如tomcat
编写测试类
package com.look.utest; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import com.look.service.IService; import com.protal.model.RequestCondition; public class Test { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(IService.class); factory.setAddress("http://localhost:8080/PortalService/services/test"); IService client = (IService) factory.create(); RequestCondition requestCondition = new RequestCondition(); requestCondition.setAge("18"); String msg = client.test(requestCondition); System.out.println(msg); } }
--------------------------测试结果----------------------------
十月 24, 2013 4:16:10 下午 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass 信息: Creating Service {http://service.look.com/}IServiceService from class com.look.service.IService 十月 24, 2013 4:16:10 下午 org.apache.cxf.services.IServiceService.IServicePort.IService 信息: Outbound Message --------------------------- ID: 1 Address: http://localhost:8080/PortalService/services/test Encoding: UTF-8 Http-Method: POST Content-Type: text/xml Headers: {Accept=[*/*], SOAPAction=[""]} Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:test xmlns:ns2="http://service.look.com/"><arg0><age>18</age></arg0></ns2:test></soap:Body></soap:Envelope> -------------------------------------- 十月 24, 2013 4:16:10 下午 org.apache.cxf.services.IServiceService.IServicePort.IService 信息: Inbound Message ---------------------------- ID: 1 Response-Code: 200 Encoding: UTF-8 Content-Type: text/xml;charset=UTF-8 Headers: {Content-Length=[214], content-type=[text/xml;charset=UTF-8], Date=[Thu, 24 Oct 2013 08:16:10 GMT], Server=[Apache-Coyote/1.1]} Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:testResponse xmlns:ns2="http://service.look.com/"><return>年龄是:18</return></ns2:testResponse></soap:Body></soap:Envelope> -------------------------------------- 年龄是:18
上一篇的测试,在本地会成功,但是将测试代码放入其他工程中就会报错的,首先编译就通不过,因为需要加载
factory.setServiceClass(CloudDataService.class);
那么如何实现CXF的网络访问呢,这就是本文要讨论的问题。
在apache-cxf-2.7.7/bin目录下有一个wsdl2java命令,这个命令可以按照wsdl文件制定的规则来生成java客户端和服务器端的代码,
这里我们只需要客户端的代码就可以了。
首先一个问题,如何得到wsdl文件?
在浏览器访问我们之前的webservice,可以看到如下图示
在url后面加上?wsdl,再次访问,我们得到另一个页面
(由于篇幅问题,我只截图了一部分。)
对了,就是这个页面,它就是我们的wsdl文件中的内容。
将这个页面的内容拷贝到一个新建文件中,随便起名,最好以.wsdl结尾
例如我将它保存为IService.wsdl,并将该文件放入d盘
接下来就要用到wsdl2java了,在命令行输入
D:\tool\apache-cxf-2.7.7\bin>wsdl2java -p com.look.test -d d:\test -client d:\IService.wsdl
意思是执行wsdl2java命令,以IService.wsdl文件为原型构建client所需要的类,并将生成的类放入d:\test目录下,目录结构为test\com\look\test
执行完毕我们会看到生成了一堆java文件如下
复制整个com目录,粘贴到你要进行客户端调用的工程中,直接运行IService.IservicePort_Client.java就会看到结果。
注意:因为本例使用的是自建类型RequestCondition作为参数,IService.IservicePort_Client.java会默认创建一个null的
RequestCondition对象,这样运行时会导致报错,我们需要修改一下,
RequestCondition requestCondition = new RequestCondition();
requestCondition .setAge("18");
另外要注意使用wsdl2java生成java代码时,要看一下使用的jdk环境,如果使用的是1.7的jdk版本,生成的代码放到jdk为1.6的项目中就会报错。
再做测试(这个测试就可以是网络访问了,可以另找一台机器测试),大功告成!
如果项目中,想要用CXF提供webService服务,又想使用Spring做依赖注入和AOP,Spring能将CXF整合么,答案是肯定的。
看下面的web.xml配置<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>cxfTest</display-name> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- cfx webSerivice --> <servlet> <servlet-name>cxf</servlet-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <load-on-startup>1</load-on-startup> </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>
是的,这个配置没有什么特别的,在原有的cxf配置基础上,加入了spring的配置,但是注意<context-param>的配置,使得cxf-servlet.xml不是必须的文件了,也就是我们可以在applicationContext.xml中进行CXF的配置。applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd "> <!-- 配置Service实现类以及dao实现类 --> <bean id="IServiceImpl" class="com.look.service.IServiceImpl"> <property name="idao" ref="idaoImpl"></property> </bean> <bean id="idaoImpl" class="com.look.dao.IDaoImpl" /> <!-- cxf webservice 服务 配置 begin --> <!--serviceClass定义了webService服务的入口,address定义了请求的名称 --> <jaxws:server id="IService" serviceClass="com.look.service.IService" address="/IService"> <jaxws:serviceBean> <ref bean="IServiceImpl"/><!-- 引用IServiceImpl实现 IService接口--> </jaxws:serviceBean> </jaxws:server> </beans>
有些文章中还引用了下面的配置
<!-- 引入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"/>
在我的配置中,我没有引入他们,也没有任何的报错信息,这里我就不引入了,有兴趣的朋友可以自己研究一下
ISerivceImpl.java
package com.look.service; import javax.jws.WebMethod; import javax.jws.WebParam; import com.look.dao.IDao; import com.look.model.RequestCondition; public class IServiceImpl implements IService { private IDao idao; public IDao getIdao() { return idao; } public void setIdao(IDao idao) { this.idao = idao; } @Override @WebMethod public String test(@WebParam RequestCondition requestCondition) { // TODO Auto-generated method stub return idao.getDataFromDB()+",年龄是:"+requestCondition.getAge(); } }
package com.look.dao;
public class IDaoImpl implements IDao{
@Override
public String getDataFromDB() {
// TODO Auto-generated method stub
return "get data from db!";
}
}
使用上一篇webservice之CXF注解实现(二)中介绍的方式生成客户端代码进行测试
public static class ServletAdapter implements Controller {
private Servlet contoller;
public ServletAdapter(Servlet contoller) {
this.contoller = contoller;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
this.contoller.service(request, response);
return null;
}
}
}
private void createAndPublishEndpoint(String url, Object implementor) {
JaxWsServiceFactoryBean aegisServiceFactoryBean = new JaxWsServiceFactoryBean();
ServerFactoryBean serverFactoryBean = new ServerFactoryBean();
serverFactoryBean.setServiceBean(implementor);
serverFactoryBean.setServiceClass(AopUtils.getTargetClass(implementor));
serverFactoryBean.setAddress(url);
serverFactoryBean.setServiceFactory(aegisServiceFactoryBean);
serverFactoryBean.getServiceFactory().getServiceConfigurations()
.add(0, new AegisServiceConfiguration());
serverFactoryBean.getServiceFactory().getServiceConfigurations()
.add(1, new JaxWsServiceConfiguration());
serverFactoryBean.create();
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
Class clazz = AopUtils.getTargetClass(bean);
if (clazz.isAnnotationPresent(WebService.class)) {
WebService ws = (WebService) clazz.getAnnotation(WebService.class);
createAndPublishEndpoint(this.urlPrefix + ws.serviceName(), bean);
registerHandler(this.urlPrefix + ws.name(), new ServletAdapter(
new CXFServlet()));
} else if (this.logger.isDebugEnabled()) {
this.logger.debug("Rejected bean '" + beanName
+ "' since it has no WebService annotation");
}
return bean;
}
public class HandlerMapping extends AbstractUrlHandlerMapping implements
BeanPostProcessor {
private String urlPrefix = "/services/";
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
import java.util.List;
import javax.jws.WebService;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.cxf.aegis.databinding.AegisServiceConfiguration;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.jaxws.support.JaxWsServiceConfiguration;
import org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean;
import org.apache.cxf.service.factory.ReflectionServiceFactoryBean;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
import org.springframework.web.servlet.mvc.Controller;
<bean id="webServicesAgent" class="org.apache.cxf.spring.remoting.Jsr181HandlerMapping">
<property name="urlPrefix"><value>/</value></property>
</bean>
可以简化,不必要生成wsdl文件,直接把地址改改就可以生成客户端:
wsdl2java -p com.huawei.hacmp.security.web -d D:\services\test -client http://10.176.38.133:8080/framework/services/sysUnitWeb?wsdl
另外可以写个批处理文件生成客户端。
http://tomee.apache.org/examples-trunk/simple-webservice/README.html