Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

JAXB Architecture

Architectural Overview

The JAXB Binding Process

More about Unmarshalling

More about Marshalling

More about Validation

Representing XML Content

Java Representation of XML Schema

Binding XML Schemas

Simple Type Definitions

Default Data Type Bindings

Schema-to-Java Mapping

JAXBElement Object

Java-to-Schema Mapping

Customizing Generated Classes and Java Program Elements

Schema-to-Java

Java-to-Schema

JAXB Examples

JAXB Compiler Options

JAXB Schema Generator Option

About the Schema-to-Java Bindings

Schema-Derived JAXB Classes

Comment Class

Items Class

ObjectFactory Class

PurchaseOrder Class

PurchaseOrderType Class

USAddress Class

Basic JAXB Examples

Modify Marshal Example

Building and Running the Modify Marshal Example Using NetBeans IDE

Building and Running the Modify Marshal Example Using Ant

Unmarshal Validate Example

Building and Running the Unmarshal Validate Example Using NetBeans IDE

Building and Running the Unmarshal Validate Example Using Ant

Customizing JAXB Bindings

Why Customize?

Customization Overview

Inline and External Customizations

Scope, Inheritance, and Precedence

Customization Syntax

Customization Namespace Prefix

Customize Inline Example

Building and Running the Customize Inline Example Using NetBeans IDE

Building and Running the Customize Inline Example Using Ant

Customized Schema

Global Binding Declarations

Schema Binding Declarations

Class Binding Declarations

Property Binding Declarations

MyDatatypeConverter Class

Datatype Converter Example

Building and Running the Datatype Converter Example Using NetBeans IDE

Building and Running the Datatype Converter Example Using Ant

Binding Declaration Files

JAXB Version, Namespace, and Schema Attributes

Global and Schema Binding Declarations

Class Declarations

External Customize Example

Building and Running the External Customize Example Using NetBeans IDE

Building and Running the External Customize Example Using Ant

Java-to-Schema Examples

Create Marshal Example

Building and Running the Create Marshal Example Using NetBeans IDE

Building and Running the Create Marshal Example Using Ant

XmlAccessorOrder Example

Using the@XmlAccessorOrder Annotation to Define Schema Element Ordering

Using the@XmlType Annotation to Define Schema Element Ordering

Schema Content Ordering in the Example

Building and Running the XmlAccessorOrder Example Using NetBeans IDE

Building and Running the XmlAccessorOrder Example Using Ant

XmlAdapter Field Example

Building and Running the XmlAdapter Field Example Using NetBeans IDE

Building and Running the XmlAdapter Field Example Using Ant

XmlAttribute Field Example

Building and Running the XmlAttribute Field Example Using NetBeans IDE

Building and Running the XmlAttribute Field Example Using Ant

XmlRootElement Example

Building and Running the XmlRootElement Example Using NetBeans IDE

Building and Running the XmlRootElement Example Using Ant

XmlSchemaType Class Example

Building and Running the XmlSchemaType Class Example Using NetBeans IDE

Building and Running the XmlSchemaType Class Example Using Ant

XmlType Example

Building and Running the XmlType Example Using NetBeans IDE

Building and Running the XmlType Example Using Ant

Further Information about JAXB

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

JAXB Examples

The sections that follow provide instructions for using the example Java applications thatare included in thetut-install/javaeetutorial5/examples/jaxb/ directory. These examples demonstrate and build uponkey JAXB features and concepts. Follow these procedures in the order presented.

After reading this section, you should feel comfortable enough with JAXB that youcan:

  • Generate JAXB Java classes from an XML schema

  • Use schema-derived JAXB classes to unmarshal and marshal XML content in a Java application

  • Create a Java content tree from scratch using schema-derived JAXB classes

  • Validate XML content during unmarshalling and at runtime

  • Customize JAXB schema-to-Java bindings

This chapter describes three sets of examples:

  • The Basic examples (Modify Marshal, Unmarshal Validate) demonstrate basic JAXB concepts like unmarshalling, marshalling, and validating XML content using default settings and bindings.

  • The Customize examples (Customize Inline, Datatype Converter, External Customize) demonstrate various ways of customizing the default binding of XML schemas to Java objects.

  • The Java-to-Schema examples show how to use annotations to map Java classes to XML schema.


    Note -The Basic and Customize examples are based on a Purchase Order scenario. Each uses an XML document,po.xml, written against an XML schema,po.xsd. These documents are derived from theW3C XML Schema Part 0: Primer, edited by David C. Fallside.


The Basic and Customize example directories contain several base files:

  • po.xsd is the XML schema you will use as input to the JAXB binding compiler, and from which schema-derived JAXB Java classes will be generated. For the Customize Inline and Datatype Converter examples, this file contains inline binding customizations.

  • po.xml is thePurchase Order XML file containing sample XML content, and is the file you will unmarshal into a Java content tree in each example. This file is almost exactly the same in each example, with minor content differences to highlight different JAXB concepts.

  • Main.java is the main Java class for each example.

  • build.xml is an Ant project file provided for your convenience. Use the Ant tool to generate, compile, and run the schema-derived JAXB classes automatically. Thebuild.xml file varies across the examples.

  • MyDatatypeConverter.java in theinline-customize example is a Java class used to provide custom data type conversions.

  • binding.xjb in the External Customize example is an external binding declarations file that is passed to the JAXB binding compiler to customize the default JAXB bindings.

Table 17-9,Table 17-10, andTable 17-11 briefly describe the Basic, Customize, and Java-to-Schema JAXBexamples.

Table 17-9 Basic JAXB Examples

Example Name

Description

Modify Marshal Example

Demonstrates how to modify a Java content tree.

Unmarshal Validate Example

Demonstrates how to enablevalidation during unmarshalling.

Table 17-10 Customize JAXB Examples

Example Name

Description

Customize Inline Example

Demonstrates how to customize the default JAXB bindings byusing inline annotations in an XML schema.

Datatype Converter Example

Similar to the Customize Inline example, thisexample illustrates alternate, more terse bindings of XMLsimpleType definitions to Java data types.

External Customize Example

Illustrateshow to use an external binding declarations file to pass binding customizations fora read-only schema to the JAXB binding compiler.

Table 17-11 Java-to-Schema JAXB Examples

Example Name

Description

Create Marshal Example

Illustrates how to marshaland unmarshal JAXB-annotated classes to XML schema. The example also shows how toenable JAXP 1.3 validation at unmarshal time using a schema file that wasgenerated from the JAXB mapped classes.

XmlAccessorOrder Example

Illustrates how to use the@XmlAccessorOrder and@XmlType.propOrder mapping annotations in Java classes to control the order in which XMLcontent is marshalled/unmarshalled by a Java type.

XmlAdapter Field Example

Illustrates how to use the interfaceXmlAdapter and the annotation@XmlJavaTypeAdapter to provide a a custom mapping of XML contentinto and out of aHashMap (field) that uses anint as thekey and aString as the value.

XmlAttribute Field Example

Illustrates how to use the annotation@XmlAttributeto define a property or field to be handled as an XML attribute.

XmlRootElement Example

Illustrateshow to use the annotation@XmlRootElement to define an XML element name forthe XML schema type of the corresponding class.

XmlSchemaType Class Example

Illustrates how to use theannotation@XmlSchemaType to customize the mapping of a property or field to anXML built-in type.

XmlType Example

Illustrates how to use the annotation@XmlType to map a classorenum type to an XML schema type.

JAXB Compiler Options

The JAXB XJC schema binding compiler transforms, or binds, a source XML schemato a set of JAXB content classes in the Java programming language. Thecompiler,xjc, is provided in two flavors in the Application Server:xjc.sh(Solaris/Linux) andxjc.bat (Windows). Bothxjc.sh andxjc.bat take the same command-line options. Youcan display quick usage instructions by invoking the scripts without any options, orwith the-help switch. The syntax is as follows:

xjc [-options ...]schema

Thexjc command line options are as follows:

-nv

Do not perform strict validation of the input schema or schemas. By default,xjc performs strict validation of the source schema before processing. Note that this does not mean the binding compiler will not perform any validation; it simply means that it will perform less-strict validation.

-extension

By default, the XJC binding compiler strictly enforces the rules outlined in the Compatibility chapter of the JAXB Specification. In the default (strict) mode, you are also limited to using only the binding customizations defined in the specification. By using the-extension switch, you will be allowed to use the JAXB Vendor Extensions.

-bfile

Specify one or more external binding files to process. (Each binding file must have its own-b switch.) The syntax of the external binding files is extremely flexible. You may have a single binding file that contains customizations for multiple schemas or you can break the customizations into multiple bindings files. In addition, the ordering of the schema files and binding files on the command line does not matter.

-ddir

By default,xjc will generate Java content classes in the current directory. Use this option to specify an alternate output directory. The directory must already exist;xjc will not create it for you.

-ppackage

Specify an alternate output directory. By default, the XJC binding compiler will generate the Java content classes in the current directory. The output directory must already exist; the XJC binding compiler will not create it for you.

-proxyproxy

Specify the HTTP/HTTPS proxy. The format is[user[:password]@]proxyHost[:proxyPort]. The old-host and-port options are still supported by the Reference Implementation for backwards compatibility, but they have been deprecated.

-classpatharg

Specify where to find client application class files used by the<jxb:javaType> and<xjc:superClass> customizations.

-catalogfile

Specify catalog files to resolve external entity references. Supports TR9401, XCatalog, and OASIS XML Catalog format. For more information, see the XML Entity and URI Resolvers document or examine the catalog-resolver sample application.

-readOnly

Force the XJC binding compiler to mark the generated Java sources read-only. By default, the XJC binding compiler does not write-protect the Java source files it generates.

-npa

Suppress the generation of package level annotations into**/package-info.java. Using this switch causes the generated code to internalize those annotations into the other generated classes.

-xmlschema

Treat input schemas as W3C XML Schema (default). If you do not specify this switch, your input schemas will be treated as W3C XML Schema.

-quiet

Suppress compiler output, such as progress information and warnings.

-help

Display a brief summary of the compiler switches.

-version

Display the compiler version information.

-Xlocator

Enable source location support for generated code.

-Xsync-methods

Generate accessor methods with thesynchronized keyword.

-mark-generated

Mark the generated code with the-@javax.annotation.Generated annotation.

JAXB Schema Generator Option

The JAXB Schema Generator,schemagen, creates a schema file for each namespace referencedin your Java classes. The schema generator can be launched using the appropriateschemagen shell script in thebin directory for your platform. The schema generator processesJava source files only. If your Java sources reference other classes, those sourcesmust be accessible from your system CLASSPATH environment variable, otherwise errors will occurwhen the schema is generated. There is no way to control the nameof the generated schema files.

You can display quick usage instructions by invoking the scripts without any options,or with the-help option. The syntax is as follows:

schemagen [-dpath] [java-source-files]

The-dpath option specifies the location of the processor- andjavac-generated class files.

About the Schema-to-Java Bindings

When you run the JAXB binding compiler against thepo.xsd XML schema usedin the basic examples (Unmarshal Read, Modify Marshal, Unmarshal Validate), the JAXB bindingcompiler generates a Java package namedprimer.po containing 11 classes, making atotal of 12 classes in each of the basic examples, as described inTable 17-12.

Table 17-12 Schema-Derived JAXB Classes in the Basic Examples

Class

Description

primer/po/Comment.java

Public interface extendingjavax.xml.bind.Element; binds to the global schemaelement namedcomment. Note thatJAXB generates element interfaces for all global element declarations.

primer/po/Items.java

Public interface that bindsto the schemacomplexType namedItems.

primer/po/ObjectFactory.java

Public class extendingcom.sun.xml.bind.DefaultJAXBContextImpl; used to create instancesof specified interfaces. For example, theObjectFactorycreateComment() method instantiates aCommentobject.

primer/po/PurchaseOrder.java

Public interface extendingjavax.xml.bind.Element, andPurchaseOrderType; binds to the global schemaelement namedPurchaseOrder.

primer/po/PurchaseOrderType.java

Public interface that binds to the schemacomplexType namedPurchaseOrderType.

primer/po/USAddress.java

Public interface thatbinds to the schemacomplexType namedUSAddress.

primer/po/impl/CommentImpl.java

Implementation ofComment.java

primer/po/impl/ItemsImpl.java

Implementation ofItems.java

primer/po/impl/PurchaseOrderImpl.java

Implementation ofPurchaseOrder.java

primer/po/impl/PurchaseOrderTypeImpl.java

Implementation ofPurchaseOrderType.java

primer/po/impl/USAddressImpl.java

Implementation ofUSAddress.java


Note -You should never directly use the generated implementation classes (*Impl.java in thepackagename/impl/directory). These classes cannot be referenced directly because the class names in thisdirectory are not standardized by the JAXB specification. TheObjectFactory method is theonly portable means to create an instance of a schema-derived interface. There isalso anObjectFactory.newInstance(Class JAXBinterface) method that enables you to create instances of interfaces.


These classes and their specific bindings to the source XML schema for thebasic examples are described inTable 17-13. .

Table 17-13 Schema-to-Java Bindings for the Basic Examples

XML Schema

JAXB Binding

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

PurchaseOrder.java

<xsd:element name="comment" type="xsd:string"/>

Comment.java

<xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/></xsd:complexType>

PurchaseOrderType.java

<xsd:complexType name="USAddress"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:element name="street" type="xsd:string"/> <xsd:element name="city" type="xsd:string"/> <xsd:element name="state" type="xsd:string"/> <xsd:element name="zip" type="xsd:decimal"/> </xsd:sequence><xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/></xsd:complexType>

USAddress.java

<xsd:complexType name="Items"> <xsd:sequence> <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">

Items.java

<xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/></xsd:complexType>

Items.ItemType

</xsd:element> </xsd:sequence></xsd:complexType>
<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{3}-[A-Z]{2}"/> </xsd:restriction></xsd:simpleType>
</xsd:schema>

Schema-Derived JAXB Classes

The sections that follow briefly explain the functions of the following individual classesgenerated by the JAXB binding compiler for the Basic examples:

Comment Class

InComment.java:

  • TheComment class is part of theprimer.po package.

  • Comment is a public interface that extendsjavax.xml.bind.Element.

  • Content in instantiations of this class binds to the XML schema element namedcomment.

  • ThegetValue() andsetValue() methods are used to get and set strings representing XMLcomment elements in the Java content tree.

Items Class

InItems.java:

  • TheItems class is part of theprimer.po package.

  • The class provides public interfaces forItems andItemType.

  • Content in instantiations of this class binds to the XML ComplexTypesItems and its child elementItemType.

  • Item provides thegetItem() method.

  • ItemType provides methods for:

    • getPartNum();

    • setPartNum(String value);

    • getComment();

    • setComment(java.lang.String value);

    • getUSPrice();

    • setUSPrice(java.math.BigDecimal value);

    • getProductName();

    • setProductName(String value);

    • getShipDate();

    • setShipDate(java.util.Calendar value);

    • getQuantity();

    • setQuantity(java.math.BigInteger value);

ObjectFactory Class

InObjectFactory.java:

  • TheObjectFactory class is part of theprimer.po package.

  • ObjectFactory provides factory methods for instantiating Java interfaces representing XML content in the Java content tree.

  • Method names are generated by concatenating:

    • The string constantcreate.

    • If the Java content interface is nested within another interface, then the concatenation of all outer Java class names.

    • The name of the Java content interface.

      For example, in this case, for the Java interfaceprimer.po.Items.ItemType,ObjectFactory creates the methodcreateItemsItemType().

PurchaseOrder Class

InPurchaseOrder.java:

  • ThePurchaseOrder class is part of theprimer.po package.

  • PurchaseOrder is a public interface that extendsjavax.xml.bind.Element andprimer.po.PurchaseOrderType.

  • Content in instantiations of this class binds to the XML schema element namedpurchaseOrder.

PurchaseOrderType Class

InPurchaseOrderType.java:

  • ThePurchaseOrderType class is part of theprimer.po package.

  • Content in instantiations of this class binds to the XML schema child element namedPurchaseOrderType.

  • PurchaseOrderType is a public interface that provides the following methods:

    • getItems();

    • setItems(primer.po.Items value);

    • getOrderDate();

    • setOrderDate(java.util.Calendar value);

    • getComment();

    • setComment(java.lang.String value);

    • getBillTo();

    • setBillTo(primer.po.USAddress value);

    • getShipTo();

    • setShipTo(primer.po.USAddress value);

USAddress Class

InUSAddress.java:

  • TheUSAddress class is part of theprimer.po package.

  • Content in instantiations of this class binds to the XML schema element namedUSAddress.

  • USAddress is a public interface that provides the following methods:

    • getState();

    • setState(String value);

    • getZip();

    • setZip(java.math.BigDecimal value);

    • getCountry();

    • setCountry(String value);

    • getCity();

    • setCity(String value);

    • getStreet();

    • setStreet(String value);

    • getName();

    • setName(String value);

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp