1 使用Maven创建Java Web工程,引入cxf和spring,pom.xml如下
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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
/p>
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
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全文如下
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:soap="http://cxf.apache.org/bindings/soap/"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.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">
implementor="com.liubo.test.cxf.serviceimpl.HelloWebServiceImpl"
address="/HelloWS">
5 配置完成后,部署到tomcat,启动访问http://localhost:8080/test-cxf 即可看到服务已成功发布。