Professional Documents
Culture Documents
Java API for XML-Based Web Services (JAX-WS) is the next generation Web services programming model
complimenting the foundation provided by the Java API for XML-based RPC (JAX-RPC) programming model.
Using JAX-WS, development of Web services and clients is simplified with greater platform independence for
Java applications by the use of dynamic proxies and Java annotations.
JAX-WS 2.0 is a new programming model that simplifies application development through support of a
standard, annotation-based model to develop Web Service applications and clients. The JAX-WS 2.0
specification strategically aligns itself with the current industry trend towards a more document-centric
messaging model and replaces the remote procedure call programming model as defined by JAX-RPC. While
the JAX-RPC programming model and applications are still supported by this product, JAX-RPC has limitations
and does not support various complex document-centric services. JAX-WS is the strategic programming model
for developing Web services and is a required part of the Java Platform, Enterprise Edition 5 (Java EE 5).
The implementation of the JAX-WS programming standard provides the following enhancements for
developing Web services and clients:
Annotations
JAX-WS introduces support for annotating Java classes with metadata to indicate that the Java class is
a Web service. JAX-WS supports the use of annotations based on the Metadata Facility for the Java
Programming Language (JSR 175) specification, the Web Services Metadata for the Java Platform
(JSR 181) specification and annotations defined by the JAX-WS 2.0 specification. Using annotations
within the Java source and within the Java class simplifies development of Web services by defining
some of the additional information that is typically obtained from deployment descriptor files, WSDL
files, or mapping metadata from XML and WSDL files into the source artifacts.
For example, you can embed a simple @WebService tag in the Java source to expose the bean as a Web
service.
@WebService
public class QuoteBean implements StockQuote {
public float getQuote(String sym) { ... }
}
The @WebService annotation tells the server runtime to expose all public methods on that bean as a
Web service. Additional levels of granularity can be controlled by adding additional annotations on
individual methods or parameters. Using annotations makes it much easier to expose Java artifacts as
Web services. In addition, as artifacts are created from using some of the top-down mapping tools
starting from a WSDL file, annotations are included within the source and Java classes as a way of
capturing the metadata along with the source files.
Using annotations also improves the development of Web services within a team structure because you
do not need to define every Web service in a single or common deployment descriptor as required with
JAX-RPC Web services. Taking advantage of annotations with JAX-WS Web services allows parallel
development of the service and the required metadata.
With JAX-WS, Web services are called both synchronously and asynchronously. JAX-WS adds support
for both a polling and callback mechanism when calling Web services asynchronously. Using a polling
model, a client can issue a request, get a response object back, which is polled to determine if the
server has responded. When the server responds, the actual response is retrieved. Using the callback
model, the client provides a callback handler to accept and process the inbound response object. Both
the polling and callback models enable the client to focus on continuing to process work without
waiting for a response to return, while providing for a more dynamic and efficient model to invoke
Web services.
For example, a Web service interface might have methods for both synchronous and asynchronous
requests. Asynchronous requests are identified in bold below:
@WebService
public interface CreditRatingService {
// sync operation
Score
getCreditScore(Customer customer);
// async operation with polling
Response<Score> getCreditScoreAsync(Customer customer);
// async operation with callback
Future<?> getCreditScoreAsync(Customer customer,
AsyncHandler<Score> handler);
}
The asynchronous invocation that uses the callback mechanism requires an additional input by the
client programmer. The callback is an object that contains the application code that will be executed
when an asynchronous response is received. The following is a code example for an asynchronous
callback handler:
CreditRatingService svc = ...;
Future<?> invocation = svc.getCreditScoreAsync(customerFred,
new AsyncHandler<Score>() {
public void handleResponse (
Response<Score> response)
{
Score score = response.get();
// do work here...
}
}
);
The following is a code example for an asynchronous polling client:
CreditRatingService svc = ...;
Response<Score> response = svc.getCreditScoreAsync(customerFred);
while (!response.isDone()) {
// do something while we wait
}
}
}
Refer to sections 5.2.1 and 5.3 of the JAX-WS 2.0 specification for more information on resource
injection.
Data binding with Java Architecture for XML Binding (JAXB) 2.0
JAX-WS leverages the JAXB 2.0 API and tools as the binding technology for mappings between Java
objects and XML documents. JAX-WS tooling relies on JAXB tooling for default data binding for twoway mappings between Java objects and XML documents. JAXB 2.0 data binding replaces the data
binding described by the JAX-RPC specification.
user to pass a javax.xml.transform.Source into the runtime which represents the data in a Source object
to be processed. SAAJ 1.3 now has the ability to pass an entire SOAP document across the interface
rather than just the payload itself. This is done by the client passing the SAAJ SOAPMessage object
across the interface. JAX-WS leverages the JAXB 2.0 support as the data binding technology of choice
between Java and XML.
JAX-WS annotations
Java API for XML-Based Web Services (JAX-WS) relies on the use of annotations to specify metadata
associated with Web service implementations and to simplify the development of Web services. Annotations
describe how a server-side service implementation is accessed as a Web service or how a client-side Java class
accesses Web services.
The JAX-WS programming standard introduces support for annotating Java classes with metadata that is used to
define a service endpoint application as a Web service and how a client can access the Web service. JAX-WS
supports the use of annotations based on the Metadata Facility for the Java Programming Language (Java
Specification Request (JSR) 175) specification, the Web Services Metadata for the Java Platform (JSR 181)
specification and annotations defined by the JAX-WS 2.0 (JSR 224) specification which includes JAXB
annotations. Using annotations from the JSR 181 standard, you can simply annotate the service implementation
class or the service interface and now the application is enabled as a Web service. Using annotations within the
Java source simplifies development and deployment of Web services by defining some of the additional
information that is typically obtained from deployment descriptor files, WSDL files, or mapping metadata from
XML and WSDL into the source artifacts.
Use annotations to configure bindings, handler chains, set names of portType, service and other WSDL
parameters. Annotations are used in mapping Java to WSDL and schema, and at runtime to control how the
JAX-WS runtime processes and responds to Web service invocations.
Annotations supported by JAX-WS are listed in the table below. The target for annotations is applicable for
these Java objects:
types such as a Java class, enum or interface
methods
fields representing local instance variables within a Java class
parameters within a Java method
Web Services Metadata Annotations (JSR 181)
Annotation class:
Annotation:
Properties:
Annotation class:
javax.jws.WebMethod
Annotation:
The @WebMethod annotation
denotes a method that is a Web
service operation.
Properties:
Important:
The @WebMethod
annotation is only supported
on classes that are annotated
with the @WebService
annotation.
- exclude
Specifies whether to exclude a
method from the Web service.
The default value is false.
(Boolean)
javax.jws.Oneway
javax.jws.WebParam
Annotation class:
Annotation:
Properties:
- partName
Defines the name of wsdl:part
attribute representing this
parameter. This is only used if
the operation is RPC style, or the
operation is document style and
the parameter style is BARE.
(String)
- targetNamespace
Specifies the XML namespace of
the XML element for the
parameter. Applies only for
document bindings when the
attribute maps to an XML
element. The default value is the
targetNamespace for the Web
service. (String)
- mode
The value represents the
direction the parameter flows for
this method. Valid values are IN,
INOUT, and OUT. (String)
- header
Specifies whether the parameter
is in a message header rather
than a message body. The default
value is false. (Boolean)
javax.jws.WebResult
Annotation class:
Annotation:
Properties:
for the return value. This
parameter is only used if the
operation is RPC style or if the
operation is DOCUMENT style
and the parameter style is
BARE. (String)
- header
Specifies whether the result is
carried in a header. The default
value is false. (Boolean)
- partName
Specifies the part name for the
result with RPC or
DOCUMENT/BARE operations.
The default value is
@WebResult.name. (String)
javax.jws.HandlerChain
The @HandlerChain
annotation associates the Web
service with an externally
defined handler chain.
- file
Specifies the location of the
handler chain file. The file
location is either an absolute
java.net.URL in external form or
a relative path from the class
file. (String)
- name
The @SOAPBinding
annotation specifies the
mapping of the Web service
onto the SOAP message
protocol.
Apply this annotation to a type
or methods on a client or
server Service Endpoint
Interface (SEI) or a server
endpoint implementation class
for a JavaBeans endpoint.
Annotation class:
Annotation:
The method level annotation is
limited in what it can specify
and is only used if the style
property isDOCUMENT. If
the method level annotation is
not specified, the
@SOAPBinding behavior
from the type is used.
Properties:
- use
Defines the formatting used for
messages sent to and from the
Web service. The default value is
LITERAL. ENCODED is not
supported in Feature Pack for
Web Services. (String)
- parameterStyle
Determines whether the
method's parameters represent
the entire message body or
whether parameters are elements
wrapped inside a top-level
element named after the
operation. Valid values are
WRAPPED or BARE. You can
only use the BARE value with
DOCUMENT style bindings.
The default value is WRAPPED.
(String)
Annotation:
The @BindingType annotation specifies the binding to use when
publishing an endpoint of this type.
- value
Indicate
javax.x
javax.x
javax.x
default
javax.x
(String)
Important:
You can use the @BindingType annotation on the Java bean endpoint
implementation class to enable MTOM by specifying either
javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_MTOM_BINDING or
javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING as
the value for the annotation.
javax.xml.ws.RequestWrapper
Annota
Propert
Annota
Propert
- localN
Specifie
the requ
defined
- targ
Specifie
The def
-
Specifie
Annotation class:
Annotation:
(String)
javax.xml.ws.ResponseWrapper
Annota
Propert
- localN
Specifie
the requ
Respon
annotat
- targ
Specifie
The def
-
Specifie
(String)
javax.xml.ws.ServiceMode
javax.xml.ws.WebFault
Annota
Propert
Important:
- value
Indicate
messag
default
Annota
Propert
- name
Specifie
corresp
specifie
- targ
Specifie
corresp
-
Specifie
javax.xml.ws.WebServiceProvider
Annota
Propert
Important:
- target
A Java class that implements a Web service must specify either the
@WebService or @WebServiceProvider annotation. Both annotations
cannot be present.
Specifie
generat
namesp
service.
- ser
Specifie
default
(String)
Annotation class:
Annotation:
operation named invoke.
The ws
Port. (S
The We
service.
JAX-WS Common Annotations (JSR 250)
Annotation class:
javax.annotation.Resource
Annotation:
The @Resource
annotation marks a
WebServiceContext
resource needed by the
application.
Properties:
The @PostConstruct
annotation marks a
method that needs to be
executed after
dependency injection is
performed on the class.
Apply this annotation to
a JAX-WS application
handler, a server
endpoint
implementation class
for a JavaBeans
endpoint or a Provider
endpoint.
javax.annotation.PreDestroy
The @PreDestroy
annotation marks a
method that must be
executed when the
instance is in the
process of being
removed by the
container.
Apply this annotation to
Annotation class:
Annotation:
Properties:
a JAX-WS application
handler, a server
endpoint
implementation class
for a JavaBeans
endpoint or a Provider
endpoint.
Rules for methods on classes annotated with @WebService
The following rules apply for methods on classes annotated with the @WebService annotation.
If the @WebService annotation of an implementation class references an SEI, the implementation class
must not have any @WebMethod annotations.
All public methods for an SEI are considered exposed methods regardless of whether the
@WebMethod annotation is specified or not. It is incorrect to have an @WebMethod annotation on an
SEI that contains the exclude attribute.
For an implementation class that does not reference an SEI, if the @WebMethod annotation is specified
with a value of exclude=true, that method is not exposed. If the @WebMethod annotation is not
specified, all public methods are exposed including the inherited methods with the exception of
methods inherited from java.lang.Object.
JAX-WS application packaging
You can package a Java Application Programming Interface (API) for XML Web Services (JAX-WS)
application as a Web service. A JAX-WS Web service is contained within a Web archive (WAR) file or a WAR
module within an enterprise archive (EAR) file.
A JAX-WS enabled WAR file contains:
A WEB-INF/web.xml file
Annotated classes that implement the Web services contained in the application module
[Optional] Web Services Description Language (WSDL) documents that describe the Web services
contained in the application module
A WEB-INF/web.xml file is similar to this example:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
</web-app>
The web.xml might contain servlet or servlet-mapping elements. When customizations to the web.xml file are
not needed, the WebSphere Application Server runtime defines them dynamically as the module is loaded. For
more information on configuring the web.xml file, read about customizing Web URL patterns in the web.xml
file for JAX-WS applications.
Annotated classes must contain, at a minimum, a Web service implementation class that includes the
@WebService annotation. The definition and specification of the Web services-related annotations are provided
by the JAX-WS and JSR-181 specifications. The Web service implementation classes can exist within the WEBINF/classes or directory within a Java archive (JAR) file that is contained in the WEB-INF/lib directory of the
WAR file.
You can optionally include WSDL documents in the JAX-WS application packaging. If the WSDL document for
a particular Web service is omitted, then the WebSphere Application Server runtime constructs the WSDL
definition dynamically from the annotations contained in the Web service implementation classes. You must
include the @WebService, @WebMethod, @WebParam, @WebResult, and optionally the @SOAPBinding
annotations if the WSDL document is omitted.
JAXB
Java Architecture for XML Binding (JAXB) is a Java technology that provides an easy and convenient way to
map Java classes and XML schema for simplified development of Web services. JAXB leverages the flexibility
of platform-neutral XML data in Java applications to bind XML schema to Java applications without requiring
extensive knowledge of XML programming.
WebSphere Application Server Version 6.1 Feature Pack for Web Services provides JAXB 2.0 standards.
JAXB is an XML to Java binding technology that supports transformation between schema and Java objects and
between XML instance documents and Java object instances. JAXB consists of a runtime application
programming interface (API) and accompanying tools that simplify access to XML documents. JAXB also helps
to build XML documents that both conform and validate to the XML schema.
JAXB provides the xjc schema compiler tool, the schemagen schema generator tool, and a runtime framework.
You can use the xjc schema compiler tool to start with an XML schema definition (XSD) to create a set of
JavaBeans that map to the elements and types defined in the XSD schema. You can also start with a set of
JavaBeans and use the schemagen schema generator tool to create the XML schema. Once the mapping between
XML schema and Java classes exists, XML instance documents can be converted to and from Java objects
through the use of the JAXB binding runtime API. Data stored in XML documents can be accessed without the
need to understand the data structure. You can then use the resulting Java classes to assemble a Web services
application.
JAXB annotated classes and artifacts contain all the information needed by the JAXB runtime API to process
XML instance documents. The JAXB runtime API supports marshaling of JAXB objects to XML and
unmarshaling the XML document back to JAXB class instances. Optionally, you can use JAXB to provide XML
validation to enforce both incoming and outgoing XML documents to conform to the XML constraints defined
within the XML schema.
JAXB is the default data binding technology used by the Java API for XML Web Services (JAX-WS) 2.0
tooling and implementation within this product. You can develop JAXB objects for use within JAX-WS
applications.
You can also use JAXB independently of JAX-WS when you want to leverage the XML data binding
technology to manipulate XML within your Java applications.
The following diagram illustrates the JAXB architecture.
Figure 1. JAXB architecture
Generate an XML schema from a Java class. Use the schema generator schemagen command to
generate an XML schema from Java classes.
Generate Java classes from an XML schema. Use the schema compiler xjc command to create a set of
JAXB-annotated Java classes from an XML schema.
Marshal and unmarshal XML documents. After the mapping between XML schema and Java classes
exists, use the JAXB binding runtime to convert XML instance documents to and from Java objects.
Results
You now have JAXB objects that your Java application can use to manipulate XML data.
Using JAXB tools to generate an XML schema file from a Java class
Use Java Architecture for XML Binding (JAXB) tooling to generate an XML schema file from Java classes.
Before you begin
Identify the Java classes or a set of Java objects to map to an XML schema file.
About this task
Use JAXB APIs and tools to establish mappings between an Java classes and XML schema. XML schema
documents describe the data elements and relationships in an XML document. After a data mapping or binding
exists, you can convert XML documents to and from Java objects. You can now access data stored in an XML
document without the need to understand the data structure.
You can create an XML schema document from an existing Java application that represents the data elements of
a Java application by using the JAXB schema generator, schemagen command-line tool. The JAXB schema
generator processes either Java source files or class files. Java class annotations provide the capability to
customize the default mappings from existing Java classes to the generated schema components. The XML
schema file along with the annotated Java class files contain all the necessary information that the JAXB
runtime requires to parse the XML documents for marshaling and unmarshaling.
Procedure
1.
Locate the annotated Java source files or Java class files to use in generating an XML schema file.
Ensure that all classes referenced by your Java class files are contained in the classpath definition or are
provided to the tool using the-classpath/-cp options.
2.
Use the JAXB schema generator, schemagen command to generate an XML schema. The schema
generator is located in the app_server_root\bin\ directory.
Results
Now that you have generated an XML schema file from Java classes, you are ready to marshal and unmarshal
the Java objects as XML instance documents.
Avoid trouble: The schemagen command does not differentiate the XML namespace between multiple
XMLType annotations that have the same @XMLType name defined within different Java packages. When this
scenario occurs, the following error is produced:
Error: Two classes have the same XML type name ....
Use @XmlType.name and @XmlType.namespace to assign different names to them...
This error indicates you have class names or @XMLType.name values that have the same name, but exist within
different Java packages. To prevent this error, add the @XML.Type.namespace class to the existing @XMLType
annotation to differentiate between the XML types.gotcha
Example
The following example illustrates how JAXB tooling can generate an XML schema file from an existing Java
class, Bookdata.java.
1. Copy the following Bookdata.java file to a temporary directory.
2. package generated;
3.
4. import javax.xml.bind.annotation.XmlAccessType;
5. import javax.xml.bind.annotation.XmlAccessorType;
6. import javax.xml.bind.annotation.XmlAttribute;
7. import javax.xml.bind.annotation.XmlElement;
8. import javax.xml.bind.annotation.XmlType;
9. import javax.xml.datatype.XMLGregorianCalendar;
10.
11.
12.
13. @XmlAccessorType(XmlAccessType.FIELD)
14. @XmlType(name = "bookdata", propOrder = {
15.
"author",
16.
"title",
17.
"genre",
18.
"price",
19.
"publishDate",
20.
"description"
21. })
22. public class Bookdata {
23.
24.
@XmlElement(required = true)
25.
protected String author;
26.
@XmlElement(required = true)
27.
protected String title;
28.
@XmlElement(required = true)
29.
protected String genre;
30.
protected float price;
31.
@XmlElement(name = "publish_date", required = true)
32.
protected XMLGregorianCalendar publishDate;
33.
@XmlElement(required = true)
34.
protected String description;
35.
@XmlAttribute
36.
protected String id;
37.
38.
public String getAuthor() {
39.
return author;
40.
}
41.
public void setAuthor(String value) {
42.
this.author = value;
43.
}
44.
public String getTitle() {
45.
return title;
46.
}
47.
48.
public void setTitle(String value) {
49.
this.title = value;
50.
}
51.
52.
53.
public String getGenre() {
54.
return genre;
55.
}
56.
57.
public void setGenre(String value) {
58.
this.genre = value;
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
}
public float getPrice() {
return price;
}
public void setPrice(float value) {
this.price = value;
}
public XMLGregorianCalendar getPublishDate() {
return publishDate;
}
public void setPublishDate(XMLGregorianCalendar value) {
this.publishDate = value;
}
public String getDescription() {
return description;
}
public void setDescription(String value) {
this.description = value;
}
public String getId() {
return id;
}
public void setId(String value) {
this.id = value;
}
}
101.Open a command prompt.
102.Run the schemagen schema generator tool from the directory where you copied the Bookdata.java file.
app_server_root\bin\schemagen.bat Bookdata.java
app_server_root/bin/schemagen.sh Bookdata.java
103.The XML schema file,schema1.xsd is generated:
104.<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
105.<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
106.
107. <xs:complexType name="bookdata">
108. <xs:sequence>
109.
<xs:element name="author" type="xs:string"/>
110.
<xs:element name="title" type="xs:string"/>
111.
<xs:element name="genre" type="xs:string"/>
112.
<xs:element name="price" type="xs:float"/>
113.
<xs:element name="publish_date" type="xs:anySimpleType"/>
114.
<xs:element name="description" type="xs:string"/>
115. </xs:sequence>
116. <xs:attribute name="id" type="xs:string"/>
117. </xs:complexType>
118.</xs:schema>
Refer to the JAXB 2.0 Reference implementation documentation for additional information about the
schemagen command.
Using JAXB tools to generate JAXB classes from an XML schema file
Use Java Architecture for XML Binding (JAXB) tooling to compile an XML schema file into fully annotated
Java classes.
Before you begin
Develop or obtain an XML schema file.
About this task
Use JAXB APIs and tools to establish mappings between an XML schema and Java classes. XML schemas
describe the data elements and relationships in an XML document. After a data mapping or binding exists, you
can convert XML documents to and from Java objects. You can now access data stored in an XML document
without the need to understand the data structure.
You can generate fully annotated Java classes from an XML schema file by using the JAXB schema compiler,
xjc command-line tool. The resulting annotated Java classes contain all the necessary information that the JAXB
runtime requires to parse the XML for marshaling and unmarshaling. You can use the resulting JAXB classes
within Java API for XML Web Services (JAX-WS) applications or in your non-JAX-WS Java applications for
processing XML data.
Procedure
1.
Use the JAXB schema compiler, xjc command to generate JAXB-annotated Java classes. The schema
compiler is located in the app_server_root\bin\ directory. The schema compiler produces a set of
packages containing Java source files and JAXB property files depending on the binding options used
for compilation.
2.
(Optional) Use custom binding declarations to change the default JAXB mappings. Define binding
declarations either in the XML schema file or in a separate bindings file. You can pass custom binding
files by using the -b option with the xjc command.
3.
Compile the generated JAXB objects. To compile generated artifacts, add the Thin Client for JAX-WS
with WebSphere Application Server to the classpath.
Results
Now that you have generated JAXB objects, you can write Java applications using the generated JAXB objects
and manipulate the XML content through the generated JAXB classes.
Example
The following example illustrates how JAXB tooling can generate Java classes when starting with an existing
XML schema file.
1. Copy the following bookSchema.xsd schema file to a temporary directory.
2.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
3.
<xsd:element name="CatalogData">
4.
<xsd:complexType >
5.
<xsd:sequence>
6.
<xsd:element name="books" type="bookdata" minOccurs="0"
7.
maxOccurs="unbounded"/>
8.
</xsd:sequence>
9.
</xsd:complexType>
10.
</xsd:element>
11.
<xsd:complexType name="bookdata">
12.
<xsd:sequence>
13.
<xsd:element name="author" type="xsd:string"/>
14.
<xsd:element name="title" type="xsd:string"/>
15.
<xsd:element name="genre" type="xsd:string"/>
16.
<xsd:element name="price" type="xsd:float"/>
17.
<xsd:element name="publish_date" type="xsd:dateTime"/>
18.
<xsd:element name="description" type="xsd:string"/>
19.
</xsd:sequence>
20.
<xsd:attribute name="id" type="xsd:string"/>
21.
</xsd:complexType>
22. </xsd:schema>
23. Open a command prompt.
24. Run the JAXB schema compiler, xjc command from the directory where the schema file is located. The
xjc schema compiler tool is located in the app_server_root\bin\ directory.
app_server_root\bin\xjc.bat bookSchema.xsd
app_server_root/bin/xjc.sh bookSchema.xsd
Running the xjc command generates the following JAXB Java files:
generated\Bookdata.java
generated\CatalogdData.java
generated\ObjectFactory.java
25. Use the generated JAXB objects within a Java application to manipulate XML content through the
generated JAXB classes.
Refer to the JAXB 2.0 Reference implementation documentation for additional information about the xjc
command.
Using the JAXB runtime to marshal and unmarshal XML documents
Use the Java Architecture for XML Binding (JAXB) runtime to manipulate XML instance documents.
Before you begin
Use JAXB to generate Java classes from an XML schema with the schema compiler, xjc command or to
generate an XML schema from a Java class with the schema generator, schemagen command.
About this task
Use JAXB APIs and tools to establish mappings between an XML schema and Java classes. After data bindings
exist, use the JAXB binding runtime API to convert XML instance documents to and from Java objects. Data
stored in an XML document is accessible without the need to understand the data structure. JAXB annotated
classes and artifacts contains all the information that the JAXB runtime API needs to process XML instance
documents. The JAXB runtime API enables marshaling of JAXB objects to XML and unmarshaling the XML
document back to JAXB class instances.
Procedure
This example demonstrates how to instantiate the generated JAXB objects within an application and
use the JAXBContext class and the JAXB runtime marshaller APIs to marshal the JAXB objects into
XML instances.
JAXBContext jc = JAXBContext.newInstance("myPackageName");
//Create marshaller
Marshaller m = jc.createMarshaller();
//Marshal object into file.
m.marshal(myJAXBObject, myOutputStream);
The JAXB Reference Implementation introduces additional vendor specific marshaller properties such
as namespace prefix mapping, indentation, and character escaping control that are not defined by the
JAXB specification. Use these properties to specify additional controls of the marshaling process.
These properties operate with the JAXB Reference Implementation only and might not with other
JAXB providers. Additional information regarding the vendor specific properties is located in the Java
Architecture for XML Binding JAXB RI Vendor Extensions Runtime Properties specification.
This example demonstrates a program that reads an XML document and unmarshals or converts the
XML document into JAXB object instances. Use the JAXBContext class and JAXB runtime
Unmarshaller APIs to unmarshal the XML document.
JAXBContext jc = JAXBContext.newInstance("myPackageName");
//Create unmarshaller
Unmarshaller um = jc.createUnmarshaller();
//Unmarshal XML contents of the file myDoc.xml into your Java
object instance.
MyJAXBObject myJAXBObject = (MyJAXBObject)
um.unmarshal(new java.io.FileInputStream( "myDoc.xml" ));
Results
You can now marshal JAXB Java classes, and unmarshal XML data using the JAXB binding framework. Refer
to the JAXB 2.0 Reference implementation documentation for additional information about the marshal and
unmarshal runtime APIs.