CXF學習筆記

學習新東西要養成寫博客的習慣:

一、新建web工程CXFDemo,作爲服務端,如下所示:

wKiom1XOvwmDl2ecAAJqMA77J08230.jpg


IHelloService.java 接口:

import javax.jws.WebService;

 

/**

 * <p>

 * WebService接口

 * </p>

 * 

 * @author IceWee

 * @date 2012-7-6

 * @version 1.0

 */

@WebService

public interface IHelloService {

 

    public String sayHello(String username);

    

}

HelloServiceImpl 實現:

/**

 * <p>

 * WebService實現類

 * </p>

 * 

 * @author IceWee

 * @date 2012-7-6

 * @version 1.0

 */

@WebService(endpointInterface = "bing.server.IHelloService", serviceName = "HelloService")

public class HelloServiceImpl implements IHelloService {

 

    @Override

    public String sayHello(String username) {

    System.out.println(username);

        return "hello, " + username;

    }

 

}

 

applicationContext-server.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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

                       http://www.springframework.org/schema/beans/spring-beans.xsd

                       http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <!-- 

        ***注意*** 

        手動添加的內容:

        xmlns:jaxws="http://cxf.apache.org/jaxws"

        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"

     -->

    

    <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" />

 

    <jaxws:endpoint id="helloService" implementor="bing.server.HelloServiceImpl" address="/helloService" />

        

</beans>

到此servcie端就已經寫好了。

下面是client端的內容,有兩種方式訪問:

 

public class HelloServiceClient {

 

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(

"applicationContext-client.xml");

IHelloService helloService = (IHelloService) context.getBean("client");

String response = helloService.sayHello("Peter");

System.out.println(response);

}

}

如果把client端的代碼和service端寫在一起,如上圖可以訪問了,如果client的代碼是另外一個獨立的工程就要把service的代碼打成jar包,引入到client工程裏。

小結:這種調用service的好處在於調用過程非常簡單,就幾行代碼就完成一個webservice的調用,但是客戶端也必須依賴服務器端的接口,這種調用方式限制是很大的,要求服務器端的webservice必須是java實現--這樣也就失去了使用webservice的意義

二、使用JaxWsDynamicClientFactory類,只要指定服務器端wsdl文件的位置,然後指定要調用的方法和方法的參數即可@Test

public void client2() throws Exception {

JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory

.newInstance();

Client client = clientFactory

.createClient("http://localhost:8080/CXFDemo/ws/helloService?wsdl");

Object[] result = client.invoke("sayHello""Sqs");

System.out.println(result[0]);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章