适用场景: 需要整合Web项目,无法集成Spring时的最佳选择。
服务器端代码:
package com.what21.cxf.http;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface IHello {
@WebMethod
public String message(String text)throws Exception;
}
package com.what21.cxf.http;
public class HelloService implements IHello {
public String message(String text) throws Exception {
return text;
}
}
package com.what21.cxf.http;
import javax.servlet.ServletConfig;
import javax.xml.ws.Endpoint;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;
public class WsServlet extends CXFNonSpringServlet {
private static final long serialVersionUID = -5449100738265954474L;
@Override
protected void loadBus(ServletConfig sc) {
super.loadBus(sc);
// 发布 http://127.0.0.1:8080/cxf/helloService?wsdl
Endpoint endpoint = Endpoint.publish("/helloService", new HelloService());
EndpointImpl epi = (EndpointImpl)endpoint;
// 添加服务器端in log拦截器
epi.getInInterceptors().add(new LoggingInInterceptor());
// 添加服务器端out log拦截器
epi.getOutInterceptors().add(new LoggingOutInterceptor());
}
}
web.xml配置servlet:
WsServlet
com.what21.cxf.http.WsServlet
1
WsServlet
/*
服务器端需要最少的jar包:
cxf-2.7.15.jar
xmlschema-core-2.1.0.jar
wsdl4j-1.6.3.jar
neethi-3.0.3.jar
asm-3.3.1.jar
woodstox-core-asl-4.4.1.jar
stax2-api-3.1.4.jar
客户端代码案例:
package com.what21.cxf.http;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class HttpWSClient {
/**
* @param args
*/
public static void main(String[] args) {
JaxWsProxyFactoryBean soapFactoryBean = new JaxWsProxyFactoryBean();
soapFactoryBean.setAddress("http://127.0.0.1:8080/cxf/helloService");
soapFactoryBean.setServiceClass(IHello.class);
soapFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
soapFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
Object o = soapFactoryBean.create();
IHello helloService = (IHello)o;
String result = null;
try {
result = helloService.message("i am client!");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
}
}
客户端调用需要最少的jar包:
cxf-2.7.15.jar
xmlschema-core-2.1.0.jar
wsdl4j-1.6.3.jar
neethi-3.0.3.jar
asm-3.3.1.jar
woodstox-core-asl-4.4.1.jar
stax2-api-3.1.4.jar