In this exercise we will experiment with different return types from a web service.
Level of Difficulty: 3 (medium)
Estimated time: 40 minutes
Pre-requisites:
JAX-WS defines the following simple Java datatypes to an equivalent in XML schema.
See Java Enterprise in a Nutshell, 3rd Ed, chapter 12 for a more complete list.
Java Types | XML Type: Document-Literal |
---|---|
boolean, java.lang.Boolean | xsd:boolean |
byte, java.lang.Byte | xsd:byte |
double, java.lang.Double | xsd:double |
float, java.lang.Float | xsd:float |
int, java.lang.Integer | xsd:integer |
long, java.lang.Long | xsd:long |
short, java.lang.Short | xsd:short |
java.lang.String | xsd:string |
java.math.BigDecimal | xsd:decimal |
java.math.BigInteger | xsd:int |
java.net.URI | xsd:anyURI |
java.util.Calendar | xsd:dateTime |
java.util.Date | xsd:dateTime |
java.xml.QName | xsd:QName |
byte[] | xsd:base64Binary |
Object | xsd:anyType |
In addition to this, it will map arrays and JavaBeans to an equivalent xsd:complexType, xsd:sequence and xsd:element combination.
We will see the impact of returning a simple object array and a more complex type such as a JavaBean.
Append the following methods into your Hello.java class
@WebMethodpublic String[] sayHellos (String mate) { String[] list = new String[3]; list[0] = "hi " + mate; list[1] = "hola " + mate; list[2] = "nihao " + mate; return list;}@WebMethodpublic Vector sayHola (String mate){ Vector<String> v = new Vector<String>(); v.add("hola " + mate); v.add("ciao " + mate); return v;}@WebMethodpublic HelloBean sayBean (String mate) { HelloBean hb = new HelloBean(); hb.setName(mate); hb.setAge(99); return hb;}
What do you notice?
Note that we now have a bunch of complexTypes named after the method names.
sayHellosResponse is a sequence with an <xsd:String> element called return. This is an array since it has a minOccurs="0" and a maxOccurs="unbounded"
So we have to write our client to cope with this - Java will just treat this as an array called return[]
sayHolaResponse is similar to sayHellosResponse but now the return type is <xs:anyType>.
So this is an Object array (since Web services doesn't understand the concept of Vector)
sayBeanResponse returns a single type: tns:helloBean
This is just saying that there is a locally defined javabean class called helloBean
Looking furthur down we see the complexType helloBean, which 2 properties (xs:int age & xs:String name)
Clientgen will conveniently generate this as a Javabean and we just use the usual setter/getters on it.
We can build a client as usual, just do remember to re-run the clientgen in the client project.
Modify your existing client to call the new methods added to your web service.
You should look at the Hello.java file (the interface).
It should contain the method signatures for sayHellos(), sayHola() and sayBean().
Notes: