前言:
大家都知道,仅仅输入或者返回一个简单型的String, Int在实际工作中没有太大的意义。很多时候我们的Service需要返回类似于List<Person>,List<String>这样的数据结构。
我们现在就一起来看用Jaxws怎么实现。
目标:
1. 用Webservice调用和返回Java的复杂类型(比如说:List<Student>这样的数据)
一、编写Server端
1.1先对jaxws返回List类型做一个简单的POC
在正式做我们的复杂类型返回前,我们先做一个试验来证明jaxws能否返回复杂类型即Collection这样的对象,我们先来试试用jaxws的webservice返回一个List<String>。
因为,webservice除简单类型如:int,string这些对象, 对于复杂类型的返回,它使用的是serialize和deserialize的机制。
即:在传送复杂对象时,webservice会把复杂类型serialize一下,在客户端得到server端的返回时再把对象deserialize出来,所以我们先用这个小实验来验证一下jaxws的serialize-deserialize的能力如何。
以下时我们的Server端代码:
package ctsjavacoe.ws.fromjava; import java.util.*; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public class CollectionWS { @WebMethod public List<String> rtnMethod() { List<String> testList = new ArrayList<String>(); testList.add("abc"); testList.add("efg"); testList.add("111"); return testList; } } |
<endpoint name='CollectionWS' implementation='ctsjavacoe.ws.fromjava.CollectionWS' url-pattern='/CollectionWSService' /> |
<servlet> <servlet-name>CollectionWS</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-name>CollectionWS</servlet-name> <url-pattern>/CollectionWSService</url-pattern> |
<?xml version="1.0" encoding="UTF-8"?> <bindings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" wsdlLocation="wsdl/CollectionWSService.wsdl" xmlns="http://java.sun.com/xml/ns/jaxws"> <bindings node="wsdl:deFinitions"> <enableAsyncMapping>true</enableAsyncMapping> </bindings> </bindings> |
package ctsjavacoe.ws.fromjava; import javax.xml.ws.Response; import java.util.*; public class CollectionWSPollingClient { public static void main(String[] args) throws Exception { CollectionWSService service = new CollectionWSService(); CollectionWS port = service.getCollectionWSPort(); Response<RtnMethodResponse> rtnMethodAsync = port.rtnMethodAsync(); while (!rtnMethodAsync.isDone()) { System.out.println("is not done"); } List<String> rtnList = new ArrayList<String>(); try { RtnMethodResponse collectionResponse = rtnMethodAsync.get(); rtnList = collectionResponse.getReturn(); System.out.println("return size======" + rtnList.size()); for (String str : rtnList) { System.out.println("output=====" + str); } } catch (Exception ex) { ex.printstacktrace(); } } } |
testList.add("abc"); testList.add("efg"); testList.add("111") |