分布式系統(tǒng)(4)---Web Service實戰(zhàn)--CXF實踐篇
來源:程序員人生 發(fā)布時間:2015-07-24 09:05:45 閱讀次數(shù):3547次
第2篇:CXF實踐篇
CXF架構(gòu)開發(fā)WebService步驟:
1、建立Web項目
2、準備所有的jar包

3、web.xml中配置cxf的核心servlet,CXFServlet
服務(wù)器端:
<display-name>cxf_demo</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-server.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
4、applicationContext-Server.xml
服務(wù)器端
<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="com.test.server.HelloWorldServerImpl"
address="/helloService" />
客戶端
<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" />
<bean id="client" class="com.test.server.IHelloWorldServer"
factory-bean="clientFactory" factory-method="create" />
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
<property name="serviceClass" value="com.test.server.IHelloWorldServer" />
<property name="address" value="http://localhost:8080/cxf_demo/ws/helloService"/>
</bean>
CXF發(fā)布服務(wù)的類有兩個:
JaxWsServerFactoryBean,我們用的這個。用于發(fā)布1個服務(wù),可以通過默許構(gòu)造實例此類。
JaxRsServerFactoryBean,此類用于發(fā)布Restful風格的webService;Restful風格是以普通get,post要求為標準的,并可以要求和相應(yīng)json數(shù)據(jù)。
5、代碼
服務(wù)器端,發(fā)布服務(wù)
IHelloWorldServer
@WebService
public interface IHelloWorldServer {
public String sayHello(String username);
}
HelloWorldServerImpl
@WebService(endpointInterface = "com.test.server.IHelloWorldServer",serviceName="HelloService")
public class HelloWorldServerImpl implements IHelloWorldServer{
@Override
public String sayHello(String username) {
return username + ":HelloWorld";
}
}
客戶端
HelloWorldClient
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-client.xml");
IHelloWorldServer helloService = (IHelloWorldServer) context.getBean("client");
String response = helloService.sayHello("liutengteng");
System.out.println(response);
}
6、運行結(jié)果
訪問地址:http://localhost:8080/cxf_demo/ws
WSDL:
客戶端運行結(jié)果:

總結(jié)
通過上面簡單的例子我們也很容易的看出來,遠程調(diào)用就是通過服務(wù)器端發(fā)布服務(wù),客戶端調(diào)用。發(fā)布出來的WSDL通過XML的情勢展現(xiàn)出來,XML解析,而且SOAP也是基于XML的。由于XML是各種語言通用的,故Web Service實現(xiàn)了跨平臺,跨語言。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈