CXF初级入门教程
以前在公司开发webservice,接触的都是axis1.4的版本,好久都没更新了。现在尝试一下使用CXF开发webservice来作为服务端,用axis来作为客户端来调用。
一、新建个web工程,导入CXF 的一些JAR包,如果使用的JDK6的版本的话,只需要如下5个Jar包(不整合spring),若是JDK5.0,可以根据下载的apache-cxf-2.4.6下的lib文件夹下有WHICH_JARS文件,里面有对这些jar包的说明。(jdk5的另加上后面带[6]标志的jar包)
commons-logging-1.1.1.jar
cxf-2.4.6.jar
neethi-3.0.1.jar
wsdl4j-1.6.2.jar
xmlschema-core-2.0.1.jar
二、在src下建个包,如com.cxf.ws,再在此包下建个HelloWord类(建个接口也可以,不过这个简单例子就直接类实现了),最后增加以下方法,如:
public String say(String text) {return "Hello World:" + text + "!";}public String[] says(String a1, String[] msgs) {String[] array = new String[msgs.length];for(int i=0; i<msgs.length; i++) {array[i] = a1 + "=>" + msgs[i];}return array;}public Long saveUser(User user) {if(null == user) {System.out.println("接收用户参数为NULL!");return null;}System.out.println("姓名:" + user.getUsername());return user.getId();}
@Overrideprotected void loadBus(ServletConfig config) {super.loadBus(config);ServerFactoryBean factory = new ServerFactoryBean();factory.setBus(getBus());factory.setServiceClass(HelloWorld.class);factory.setAddress("/hello");factory.getInInterceptors().add(new LoggingInInterceptor());factory.getOutInterceptors().add(new LoggingOutInterceptor());factory.create();}
<servlet><servlet-name>MyCXFServlet</servlet-name><servlet-class>com.cxf.MyCXFServlet</servlet-class></servlet><servlet-mapping><servlet-name>MyCXFServlet</servlet-name><url-pattern>/ws/*</url-pattern></servlet-mapping>
static void testSay() {Service service = new Service();try {Call call = (Call) service.createCall();call.setOperationStyle(Style.WRAPPED);call.setTargetEndpointAddress("http://localhost:8088/cxf/ws/hello");call.addParameter("text", XMLType.XSD_STRING, ParameterMode.IN);call.setReturnType(XMLType.XSD_STRING, String.class);String result = (String) call.invoke("say", new Object[]{"John"});System.out.println("结果:" + result);} catch (ServiceException e) {e.printStackTrace();} catch (RemoteException e) {e.printStackTrace();}}static void testSayArray() {Service service = new Service();try {Call call = (Call) service.createCall();call.setOperationStyle(Style.WRAPPED);call.setTargetEndpointAddress("http://localhost:8088/cxf/ws/hello");call.addParameter("a1", XMLType.XSD_STRING, ParameterMode.IN);call.addParameter("msgs", XMLType.XSD_STRING, String[].class, ParameterMode.IN);call.setReturnType(XMLType.XSD_STRING, String[].class);String a1 = "你好";String[] msgs = {"李四","张三","John"};String[] result = (String[]) call.invoke("says", new Object[]{a1, msgs});System.out.println("结果:");for(String r : result) {System.out.println(r);}} catch (ServiceException e) {e.printStackTrace();} catch (RemoteException e) {e.printStackTrace();}}public static void main(String[] args) {testSay();testSayArray();}