1 使用Maven创建Java Web工程,引入cxf和spring,pom.xml如下
4.0.0
com.liubo
test-cxf
0.0.1-SNAPSHOT
war
UTF-8
org.apache.cxf
cxf-rt-frontend-jaxws
2.7.3
org.springframework
spring-web
3.1.2.RELEASE
javax.servlet
servlet-api
2.5
provided
javax.servlet.jsp
jsp-api
2.1
provided
org.apache.maven.plugins
maven-compiler-plugin
2.3.2
1.6
1.6
UTF-8
org.apache.maven.plugins
maven-surefire-plugin
2.7.2
once
-Dfile.encoding=UTF-8
net.sourceforge.cobertura.datafile
target/cobertura/cobertura.ser
2 在web.xml中配置applicationContext.xml和cxf servlet
Archetype Created Web Application
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CXFServlet
CXF Servlet
org.apache.cxf.transport.servlet.CXFServlet
1
CXFServlet
/*
index.jsp
3 创建要提供服务接口和实现
接口类
package com.liubo.test.cxf.service;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService
public interface HelloWebService {
String sayHello(@WebParam(name = "text") String text);
}
实现类
package com.liubo.test.cxf.serviceimpl;
import javax.jws.WebParam;
import javax.jws.WebService;
import com.liubo.test.cxf.service.HelloWebService;
@WebService(serviceName = "HelloWS")
public class HelloWebServiceImpl implements HelloWebService {
public String sayHello(@WebParam(name = "test") String text) {
System.out.println("sayHello method called");
return "hello " + text + ", welcome to the real world";
}
}
4 配置spring文件applicationContext.xml
注意引入xmlns:jaxws和cxf.xml,
xmlns:jaxws="http://cxf.apache.org/jaxws"
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
然后添加要提供的接口信息jaxws:endpoint id="HelloWorld"
applicationContext.xml全文如下
5 配置完成后,部署到tomcat,启动访问http://localhost:8080/test-cxf 即可看到服务已成功发布。
客户端实现见下文:使用cxf-codegen-plugin实现WebServices客户端