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

Java-to-Schema Examples

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

If you are using JDK 6, perform the following steps before yourun any of the Java-to-Schema examples:

  1. Change to one of the Java-to-Schema example directories (for example,tut-install/javaeetutorial5/examples/jaxb/j2s-create-marshal.

  2. Run the following Ant command:

    ant update-endorsed

    This command creates anendorsed directory in the JDK and copies thewebservices-api.jar file from the Application Server'slib/endorsed/ directory into it.

Create Marshal Example

The Create Marshal example illustrates Java-to-schema databinding. It demonstrates marshalling and unmarshalling ofJAXB annotated classes and also shows how to enable JAXP 1.3 validation atunmarshal time using a schema file that was generated from the JAXB mappedclasses.

The schema file,bc.xsd, was generated with the following commands:

schemagen src/cardfile/*.javacp schema1.xsd bc.xsd

Note thatschema1.xsd, was copied tobc.xsd;schemagen does not allow youto specify a schema name of your choice.

Building and Running the Create Marshal Example Using NetBeans IDE

Follow these instructions to build and run the Create Marshal example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-create-marshal folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-create-marshal project and select Run.

Building and Running the Create Marshal Example Using Ant

To compile and run the Create Marshal example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/j2s-create-marshal/ directory and type the following:

ant runapp

XmlAccessorOrder Example

The j2s-xmlAccessorOrder example shows how to use the@XmlAccessorOrder and@XmlType.propOrder annotationsto dictate the order in which XML content is marshalled/unmarshalled by a Javatype.

With Java-to-schema mapping, a JavaBean’s properties and fields are mapped to an XMLSchema type. The class elements are mapped to either an XML Schema complextype or an XML Schema simple type. The default element order for agenerated schema type is currently unspecified because Java reflection does not impose areturn order. The lack of reliable element ordering negatively impacts application portability. Youcan use two annotations,@XmlAccessorOrder and@XmlType.propOrder, to define schema element ordering forapplications that need to be portable across JAXB Providers.

Using the@XmlAccessorOrder Annotation to Define Schema Element Ordering

The@XmlAccessorOrder annotation imposes one of two element ordering algorithms,AccessorOrder.UNDEFINED orAccessorOrder.ALPHABETICAL.AccessorOrder.UNDEFINED is the default setting. The order is dependent on the system’s reflectionimplementation.AccessorOrder.ALPHABETICAL orders the elements in lexicographic order as determined byjava.lang.String.CompareTo(String anotherString).

You can define the@XmlAccessorOrder annotation for annotation typeElementType.PACKAGE on a classobject. When the@XmlAccessorOrder annotation is defined on a package, the scope of theformatting rule is active for every class in the package. When defined ona class, the rule is active on the contents of that class.

There can be multiple@XmlAccessorOrder annotations within a package. The order of precedenceis the innermost (class) annotation takes precedence over the outer annotation. For example,if@XmlAccessorOrder(AccessorOrder.ALPHABETICAL) is defined on a package and@XmlAccessorOrder(AccessorOrder.UNDEFINED) is defined ona class in that package, the contents of the generated schema type forthe class would be in an unspecified order and the contents of thegenerated schema type for every other class in the package would be alphabeticalorder.

Using the@XmlType Annotation to Define Schema Element Ordering

The@XmlType annotation can be defined for a class. The annotation elementpropOrder()in the@XmlType annotation allows you to specify the content order in thegenerated schema type. When you use the@XmlType.propOrder annotation on a class to specifycontent order, all public properties and public fields in the class must bespecified in the parameter list. Any public property or field that you wantto keep out of the parameter list must be annotated with@XmlAttributeor@XmlTransient annotation.

The default content order for@XmlType.propOrder is{} or{""}, not active.In such cases, the active@XmlAccessorOrder annotation takes precedence. When class content orderis specified by the@XmlType.propOrder annotation, it takes precedence over any active@XmlAccessorOrderannotation on the class or package. If the@XmlAccessorOrder and@XmlType.propOrder(A, B, ...) annotations arespecified on a class, thepropOrder always takes precedence regardless of the order ofthe annotation statements. For example, in the code below, the@XmlAccessorOrder annotationprecedes the@XmlType.propOrder annotation.

@XmlAccessorOrder(AccessorOrder.ALPHABETICAL)@XmlType(propOrder={"name", "city"})public class USAddress {            .            .    public String getCity() {return city;}    public void setCity(String city) {this.city = city;}    public String getName() {return name;}    public void setName(String name) {this.name = name;}            .            .}

In the code below, the@XmlType.propOrder annotation precedes the@XmlAccessorOrder annotation.

@XmlType(propOrder={"name", "city"})@XmlAccessorOrder(AccessorOrder.ALPHABETICAL)public class USAddress {            .            .    public String getCity() {return city;}    public void setCity(String city) {this.city = city;}    public String getName() {return name;}    public void setName(String name) {this.name = name;}            .            .}

In both scenarios,propOrder takes precedence and the identical schema content shown belowwill be generated.

<xs:complexType name="usAddress">   <xs:sequence>        <xs:element name="name" type="xs:string" minOccurs="0"/>        <xs:element name="city" type="xs:string" minOccurs="0"/>   </xs:sequence></xs:complexType>
Schema Content Ordering in the Example

The purchase order code example demonstrates the effects of schema content ordering usingthe@XmlAccessorOrder annotation at the package and class level, and the@XmlType.propOrder annotation ona class.

Classpackage-info.java defines@XmlAccessorOrder to beALPHABETICAL for the package. The public fieldsshipTo andbillTo in classPurchaseOrderType will be affected in the generatedschema content order by this rule. ClassUSAddress defines the@XmlType.propOrder annotation onthe class. User of this annotation demonstrates user-defined property order supersedingALPHABETICAL orderin the generated schema.

The generated schema file can be found in thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlAccessorOrder/build/schemas/ directory.

Building and Running the XmlAccessorOrder Example Using NetBeans IDE

Follow these instructions to build and run the XmlAccessorOrder example on your ApplicationServer instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlAccessorOrder folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlAccessorOrder project and select Run.

Building and Running the XmlAccessorOrder Example Using Ant

To compile and run the XmlAccessorOrder example using Ant, in a terminal window,go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlAccessorOrder/ directory and type the following:

ant runapp

XmlAdapter Field Example

The XmlAdapter Field example demonstrates how to use theXmlAdapter interface andthe@XmlJavaTypeAdapter annotation to provide a custom mapping of XML content into andout of aHashMap (field) that uses anint as the key andaString as the value.

InterfaceXmlAdapter and annotation@XmlJavaTypeAdapter are used for special processing of data types duringunmarshalling/marshalling. There are a variety of XML data types for which the representationdoes not map easily into Java (for example,xs:DateTime andxs:Duration), and Java typeswhich do not map conveniently into XML representations, for example implementations ofjava.util.Collection(such asList) andjava.util.Map (such asHashMap) or for non-JavaBean classes.

TheXmlAdapter interface and the@XmlJavaTypeAdapter annotation are provided for cases suchas these. This combination provides a portable mechanism for reading/writing XML content intoand out of Java applications.

TheXmlAdapter interface defines the methods for data reading/writing.

/* *  ValueType - Java class that provides an XML representation *              of the data. It is the object that is used for *              marshalling and unmarshalling. * *  BoundType - Java class that is used to process XML content. */public abstract class XmlAdapter<ValueType,BoundType> {    // Do-nothing constructor for the derived classes.    protected XmlAdapter() {}    // Convert a value type to a bound type.    public abstract BoundType unmarshal(ValueType v);    // Convert a bound type to a value type.    public abstract ValueType marshal(BoundType v); }

You can use the@XmlJavaTypeAdapter annotation to associate a particularXmlAdapter implementation withaTarget type,PACKAGE,FIELD,METHOD,TYPE, orPARAMETER.

The XmlAdapter Field example shows how to use anXmlAdapter for mapping XMLcontent into and out of a (custom)HashMap. TheHashMap object,basket, inclassKitchenWorldBasket, uses a key of typeint and a value of typeString. These data types should be reflected in the XML content that isread and written, so the XML content should look like this.

<basket>     <entry key="9027">glasstop stove in black</entry>     <entry key="288">wooden spoon</entry></basket>

The default schema generated for Java typeHashMap does not reflect the desiredformat.

<xs:element name="basket">   <xs:complexType>     <xs:sequence>       <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">         <xs:complexType>           <xs:sequence>             <xs:element name="key" minOccurs="0" type="xs:anyType"/>             <xs:element name="value" minOccurs="0" type="xs:anyType"/>          </xs:sequence>        </xs:complexType>      </xs:element>    </xs:sequence>  </xs:complexType></xs:element>

In the defaultHashMap schema, key and value are both elements and areof data typeanyType. The XML content will look like this:

<basket>     <entry>        <key>9027</>        <value>glasstop stove in black</>     </entry>     <entry>        <key>288</>        <value>wooden spoon</>    </entry></basket>

To resolve this issue, the example uses two Java classes,PurchaseList andPartEntry, that reflect the needed schema format for unmarshalling/marshalling the content. The XMLschema generated for these classes is as follows:

<xs:complexType name="PurchaseListType">    <xs:sequence>        <xs:element name="entry" type="partEntry"            nillable="true" maxOccurs="unbounded"            minOccurs="0"/>    </xs:sequence></xs:complexType><xs:complexType name="partEntry">    <xs:simpleContent>        <xs:extension base="xs:string">            <xs:attribute name="key" type="xs:int"                use="required"/>        </xs:extension>    </xs:simpleContent></xs:complexType>

ClassAdapterPurchaseListToHashMap implements theXmlAdapter interface. In classKitchenWorldBasket, the@XmlJavaTypeAdapter annotation isused to pairAdapterPurchaseListToHashMap with fieldHashMapbasket. This pairing will cause themarshal/unmarshal method ofAdapterPurchaseListToHashMap to be called for any corresponding marshal/unmarshal actiononKitchenWorldBasket.

Building and Running the XmlAdapter Field Example Using NetBeans IDE

Follow these instructions to build and run the XmlAdapter Field example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlAdapter-field folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlAdapter-field project and select Run.

Building and Running the XmlAdapter Field Example Using Ant

To compile and run the XmlAdapter Field example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlAdapter-field/ directory and type the following:

ant runapp

XmlAttribute Field Example

The XmlAttribute Field example shows how to use the@XmlAttribute annotation to definea property or field to be treated as an XML attribute.

The@XmlAttribute annotation maps a field or JavaBean property to an XML attribute.The following rules are imposed:

  • A static final field is mapped to a XML fixed attribute.

  • When the field or property is a collection type, the items of the collection type must map to a schema simple type.

  • When the field or property is other than a collection type, the type must map to a schema simple type.

When following the JavaBean programming paradigm, a property is defined by agetandset prefix on a field name.

int zip;public int getZip(){return zip;}public void setZip(int z){zip=z;}

Within a bean class, you have the choice of setting the@XmlAttributeannotation on one of three components: the field, the setter method, or thegetter method. If you set the@XmlAttribute annotation on the field, thesetter method will need to be renamed or there will be a namingconflict at compile time. If you set the@XmlAttribute annotation on oneof the methods, it must be set on either the setter or gettermethod, but not on both.

The XmlAttribute Field example shows how to use the@XmlAttribute annotation on astatic final field, on a field rather than on one of thecorresponding bean methods, on a bean property (method), and on a field thatis other than a collection type. In classUSAddress, fields, country, and zip aretagged as attributes. ThesetZip method was disabled to avoid the compile error.Property state was tagged as an attribute on the setter method. You couldhave used the getter method instead. In classPurchaseOrderType, fieldcCardVendor isa non-collection type. It meets the requirement of being a simple type; itis anenum type.

Building and Running the XmlAttribute Field Example Using NetBeans IDE

Follow these instructions to build and run the XmlAttribute Field example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlAttribute-field folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlAttribute-field project and select Run.

Building and Running the XmlAttribute Field Example Using Ant

To compile and run the XmlAttribute Field example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlAttribute-field/ directory and type the following:

ant runapp

XmlRootElement Example

The XmlRootElement example demonstrates the use of the@XmlRootElement annotation to definean XML element name for the XML schema type of the corresponding class.

The@XmlRootElement annotation maps a class or anenum type to anXML element. At least one element definition is needed for each top-level Javatype used for unmarshalling/marshalling. If there is no element definition, there is nostarting location for XML content processing.

The@XmlRootElement annotation uses the class name as the default element name. Youcan change the default name by using the annotation attributename. If youdo, the specified name will then be used as the element name andthe type name. It is common schema practice for the element and typenames to be different. You can use the@XmlType annotation to setthe element type name.

The namespace attribute of the@XmlRootElement annotation is used to define a namespacefor the element.

Building and Running the XmlRootElement Example Using NetBeans IDE

Follow these instructions to build and run the XmlRootElement example on your ApplicationServer instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlRootElement folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlRootElement project and select Run.

Building and Running the XmlRootElement Example Using Ant

To compile and run the XmlRootElement example using Ant, in a terminal window,go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlRootElement/ directory and type the following:

ant runapp

XmlSchemaType Class Example

The XmlSchemaType Class example demonstrates the use of the annotation@XmlSchemaType tocustomize the mapping of a property or field to an XML built-in type.

The@XmlSchemaType annotation can be used to map a Java type to oneof the XML built-in types. This annotation is most useful in mapping aJava type to one of the nine date/time primitive data types.

When the@XmlSchemaType annotation is defined at the package level, the identification requiresboth the XML built-in type name and the corresponding Java type class. An@XmlSchemaType definition on a field or property takes precedence over a package definition.

The XmlSchemaType Class example shows how to use the@XmlSchemaType annotation atthe package level, on a field, and on a property. FileTrackingOrder hastwo fields,orderDate anddeliveryDate, which are defined to be of typeXMLGregorianCalendar. The generated schema will define these elements to be of XMLbuilt-in typegMonthDay. This relationship was defined on the package in the filepackage-info.java.FieldshipDate in fileTrackingOrder is also defined to be of typeXMLGregorianCalendar,but the@XmlSchemaType annotation statements override the package definition and specify the fieldto be of typedate. Property methodgetTrackingDuration defines the schema element tobe defined as primitive typeduration and not Java typeString.

Building and Running the XmlSchemaType Class Example Using NetBeans IDE

Follow these instructions to build and run the XmlSchemaType Class example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlSchemaType-class folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlSchemaType-class project and select Run.

Building and Running the XmlSchemaType Class Example Using Ant

To compile and run the XmlSchemaType Class example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlSchemaType-class/ directory and type the following:

ant runapp

XmlType Example

The XmlType example demonstrates the use of the@XmlType annotation. The@XmlType annotationmaps a class or anenum type to a XML Schema type.

A class must have either a public zero-argument constructor or a static zero-argumentfactory method in order to be mapped by this annotation. One of thesemethods is used during unmarshalling to create an instance of the class. Thefactory method may reside within in a factory class or the existing class.

There is an order of precedence as to which method is usedfor unmarshalling:

  • If a factory class is identified in the annotation, a corresponding factory method in that class must also be identified and that method will be used.

  • If a factory method is identified in the annotation but no factory class is identified, the factory method must reside in the current class. The factory method is used even if there is a public zero arg constructor method present.

  • If no factory method is identified in the annotation, the class must contain a public zero arg constructor method.

In this example, a factory class provides zero arg factory methods for severalclasses. The@XmlType annotation on classOrderContext references the factory class. Theunmarshaller will use the identified factory method in this class.

public class OrderFormsFactory {    public OrderContext newOrderInstance() {        return new OrderContext()    }    public PurchaseOrderType newPurchaseOrderType() {        return new newPurchaseOrderType();    }}@XmlType(name="oContext", factoryClass="OrderFormsFactory",  factoryMethod="newOrderInstance")public class OrderContext {    public OrderContext(){ ..... }}

In this example, a factory method is defined in a class, whichalso contains a standard class construct. Because thefactoryMethod value is defined and nofactoryClass is defined, the factory methodnewOrderInstance is used during unmarshalling.

@XmlType(name="oContext", factoryMethod="newOrderInstance") public class OrderContext {    public OrderContext(){ ..... }    public OrderContext newOrderInstance() {         return new OrderContext();    }}
Building and Running the XmlType Example Using NetBeans IDE

Follow these instructions to build and run the XmlType example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thej2s-xmlType folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thej2s-xmlType project and select Run.

Building and Running the XmlType Example Using Ant

To compile and run the XmlType example using Ant, in a terminalwindow, go to thetut-install/javaeetutorial5/examples/jaxb/j2s-xmlType/ directory and type the following:

ant runapp
PreviousContentsNext

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


[8]ページ先頭

©2009-2025 Movatter.jp