WebService的實現方式有很多,這里主要介紹關于cxf的WebService的搭建。
參考連接:http://boyadn.blog.163.com/blog/static/74230736201322104510611/
1.首先是搭建服務端
我這里服務端主要包括兩個類,一個是接口和一個是實現類。
Hello.java的具體代碼如下:
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService
public interface Hello {
@WebMethod
public String sayHello(@WebParam(name="name") String name);
}
代碼很簡單,只有一個方法sayHello。
實現類HelloImpl.java如下:
import javax.jws.WebService;
import com.lml.ws.service.Hello;
@WebService(endpointInterface = "com.lml.ws.service.Hello")
public class HelloImpl implements Hello {
public String sayHello(String name) {
return name + " say hello!";
}
}
主要是對Hello接口的實現。
因為使用了spring來管理,所以這里需要配置applicationContext,applicationContext.xml具體的代碼如下:
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">
implementor="com.lml.ws.service.Impl.HelloImpl"
address="/HelloService" />
因為有使用spring 和 cxf,所以先導入相關jar包,我導入的jar包如下:
具體的jar包和項目下載地址:http://download.csdn.net/detail/l540151663/8036439
最后在web.xml下設置攔截器:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CXFServlet
org.apache.cxf.transport.servlet.CXFServlet
1
CXFServlet
/*
到此,服務端搭建完畢。
2.客戶端的搭建WebClient
建立java項目后,在項目中導入相關jar包,如下:
服務端放入容器tomcat中,然后開啟,用url訪問頁面http://localhost:8080/WebService/HelloService?wsdl
訪問內容如下:
將該頁面另存為HelloService.xml,這里要注意,xml文件是沒有樣式的。
因為需要引用到服務端的Hello實例,所以這里需要做些處理。使用wsdl2java生成客戶端代碼。這里需要用到一個包apache-cxf-3.0.1。解壓后在C:\Users\Administrator\Desktop\apache-cxf-3.0.1\apache-cxf-3.0.1\bin下有wsdl2java文件。打開cmd,進入該bin目錄下,執行命令:C:\Users\Administrator\Desktop\apache-cxf-3.0.1\apache-cxf-3.0.1\bin>wsdl2java -
p com.lml.ws.client -d d:\workspace\WebClient\src -verbose "C:\Users\Administrat
or\Desktop\HelloService.xml"
關于上面的命令解析:
wsdl2java -p 包名 -d 生成文件路徑 -verbose "wsdl文件路徑"
包名:文件存放的包名,可以寫項目中包路徑
生成文件路徑 :文件存放路徑,可以直接寫項目路徑
wsdl文件:在IE中執行服務端URL顯示的XML另存為XML文件。
執行后刷新WebClient項目,生成內容如下圖:
最后在客戶端進行測試,Test.java代碼如下:
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.lml.ws.client.Hello;
public class Test {
public static void main(String[] args) {
//創建WebService客戶端代理工廠
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
//注冊WebService接口
factory.setServiceClass(Hello.class);
//設置WebService地址
factory.setAddress("http://localhost:8080/WebService/HelloService");
Hello helloService = (Hello)factory.create();
System.out.println("message context is:"+helloService.sayHello("lml"));
}
}
執行代碼,結果如下圖:
具體代碼和使用工具請到上面地址下載。