12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 14 ■ SOAP WEB SERVICESListing 14-6. A Main Class Marshalling a CreditCard Objectpublic class Main {public static void main(String[] args) {CreditCard creditCard = new CreditCard("1234", "12/09", 6398, "Visa");StringWriter writer = new StringWriter();JAXBContext context = JAXBContext.newInstance(CreditCard.class);Marshaller m = context.createMarshaller();m.marshal(creditCard, writer);}}System.out.println(writer.toString());Metro, the JAXB reference implementation, has other tools, specifically the schema compiler (xjc)and the schema generator (schemaGen); while marshalling/unmarshalling deals <strong>with</strong> objects and XMLdocuments, the schema compiler and the schema generator deal <strong>with</strong> classes and XML Schemas. Thesetools can be used in the command line (they are bundled <strong>with</strong> <strong>Java</strong> SE 6) or as Maven goals.With JAXB, you have two possible scenarios from which bindings arise:• Start from <strong>Java</strong> classes: The <strong>Java</strong> classes exist and are used to generate an XMLSchema.• Start from an XML Schema: In this scenario, the schema exists, and the <strong>Java</strong>classes are created using a schema compiler.These two scenarios are very important for web services. A SOAP web service can generate its WSDLfiles, and, based on that WSDL, a consumer can generate a set of <strong>Java</strong> classes, all in a transparent andportable way.AnnotationsJAXB is similar to JPA in many ways. However, instead of mapping objects to a database, JAXB does themapping to an XML document. Also, like JPA, JAXB defines a set of annotations (in thejavax.xml.bind.annotation package) to customize this mapping, and relies on configuration byexception to minimize the work of the developer. If persistent objects have to be annotated <strong>with</strong> @Entity,the correspondent in JAXB is @XmlRootElement (see Listing 14-7).Listing 14-7. A Customized CreditCard Class@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class CreditCard {425

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!