Design and Develop JAX-WS 2.0 Web Services: Section 1. Before You Start
Design and Develop JAX-WS 2.0 Web Services: Section 1. Before You Start
0 web services
Naveen Balani ([email protected])
Development Manager
IBM
Rajeev Hathi
Technical Architect
Consultant
Using Java API for XML Web Services (JAX-WS) technology to design and
develop web services yields many benefits, including simplifying the construction
of web services and web service clients in Java, easing the development and
deployment of web services, and speeding up web services development. This
tutorial walks you through how to do all of this and more by developing a sample
order-processing application that exposes its functionality as web services. After
going through this tutorial, you'll be able to apply these concepts and your newly
acquired knowledge to develop web services for your application using JAX-WS
technology.
Objectives
After going through this tutorial, you can apply the concepts and knowledge to
develop web services for your application using JAX-WS technology.
Prerequisites
To complete this tutorial successfully, you should have a basic understanding of web
services technology and have some proficiency in Java programming.
Copyright IBM Corporation 2007
Design and develop JAX-WS 2.0 web services
Trademarks
Page 1 of 16
developerWorks
ibm.com/developerWorks/
System requirements
Related content:
Web services hints and tips: JAX-RPC versus JAX-WS series
JAX-WS client APIs in the Web Services Feature Pack for
WebSphere Application Server V6.1 series
Web services on demand demos
To run the examples in this tutorial, you need Java Platform, Standard Edition (Java
SE) 6.0 installed.
Page 2 of 16
ibm.com/developerWorks/
developerWorks
javax.jws.WebMethod;
javax.jws.WebService;
javax.jws.soap.SOAPBinding;
com.ibm.jaxws.tutorial.service.bean.OrderBean;
Page 3 of 16
developerWorks
ibm.com/developerWorks/
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,
parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class OrderProcessService {
@WebMethod
public OrderBean processOrder(OrderBean orderBean) {
// Do processing...
System.out.println("processOrder called for customer"
+ orderBean.getCustomer().getCustomerId());
// Items ordered are
if (orderBean.getOrderItems() != null) {
System.out.println("Number of items is "
+ orderBean.getOrderItems().length);
}
//Process order.
//Set the order ID.
orderBean.setOrderId("A1234");
return orderBean;
}
}
The OrderBean holds the order information as shown in the Listing 2. Specifically, it
contains references to the customer, order items, and shipping address object.
Listing 2. OrderBean class holding order information
package com.ibm.jaxws.tutorial.service.bean;
public class OrderBean {
private Customer customer;
private Address shippingAddress;
private OrderItem[] orderItems;
private String orderId;
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public Address getShippingAddress() {
return shippingAddress;
}
Page 4 of 16
ibm.com/developerWorks/
developerWorks
The starting point for developing a JAX-WS web service is a Java class annotated
with the javax.jws.WebService annotation. The JAX-WS annotations used are part
of the Web Services Metadata for the Java Platform specification (JSR-181). As
you have probably noticed, OrderProcessService is annotated with the WebService
annotation, which defines the class as a web service endpoint.
The OrderProcessService class (this is the class with the @javax.jws.WebService
annotation) implicitly defines a service endpoint interface (SEI), which declares
methods that a client can invoke on the service. All the public methods defined in the
class, unless the method is annotated with a @WebMethod annotation with the exclude
element set to true, get mapped to WSDL operations. The @WebMethod annotation is
optional and used for customizing the web service operation. Apart from the exclude
element, the javax.jws.WebMethod annotation provides the operation name and
action elements, which are used to customize the name attribute of the operation
and the SOAP action element in a WSDL document. These properties are optional; if
undefined, default values are derived from the class name.
After the web service is implemented, you need to generate any artifacts required to
deploy the service, then package the web service as a deployed artifacttypically as
a WAR fileand deploy the WAR file to any compliant server that supports the JAXWS 2.0 specification. Typical artifacts generated are classes that provide conversion
of Java objects to XML, and the WSDL file and XSD schema based on the service
interface.
For testing purposes, Java 6 bundles a lightweight web server to which the web
service can be published by invoking a simple API call. Next you take a look at how
to test your web services using this approach.
Page 5 of 16
developerWorks
ibm.com/developerWorks/
the required artifacts for web service deployment and invocation. The wsgen tool
generates the WSDL file and XSD schema for the web service, which needs to be
published.
For generating the JAX-WS artifacts, you first need to compile the service and beans
sources:
1. Open a command prompt, and navigate to c:\JAXWS-Tutorial.
2. Run the following command to compile the Java files and place the class files
into their respective folders:
javac com\ibm\jaxws\tutorial\service\*.java com\ibm\jaxws\tutorial
\service\bean\*.java
The wsgen tool provides lot of options, like generating the WSDL and schema
artifacts for the service by providing the -wsdl option. After running this command,
you should see OrderProcess.wsdl and OrderProcess_schema1.xsd generated in the
JAXWS-Tutorial folder, and the JAX-WS artifacts being created in the com\ibm\jaxws
\tutorial\service\jaxws folder.
After the artifacts are generated, you publish the order-processing web service by
running the following web service publisher client.
4. Compile the OrderWebServicePublisher by running the following command from
the c:\JAXWS-Tutorial folder:
javac com\ibm\jaxws\tutorial\service\publish
\OrderWebServicePublisher.java
After running the Java program, you should see the following message: The web
service is published at http://localhost:8080/OrderProcessWeb/orderprocess.
To stop running the web service, terminate this Java process.
Page 6 of 16
ibm.com/developerWorks/
developerWorks
Page 7 of 16
developerWorks
ibm.com/developerWorks/
The wsgen tool executed earlier generates two wrapper bean classes, ProcessOrder
and ProcessOrderResponse, which hold input and output messages for the orderprocessing web service. Based on the wrapper bean classes, the following schema
elements are generated:
processOrder is of the type processOrder, which represents a complex type
containing one element with the name arg0 and the type orderBean. You can
see a one-to-one mapping between the ProcessOrder class and processOrder
complex type.
processOrderResponse is similarly of the type processOrderResponse whose
definitions map to the ProcessOrderResponse class.
Let's look more closely at that in Listing 6.
Listing 6. Schema declaration for processOrder
<xs:element name="processOrder" type="tns:processOrder"/>
<xs:element name="processOrderResponse" type="tns:processOrderResponse"/>
<xs:complexType name="processOrder">
<xs:sequence>
<xs:element name="arg0" type="tns:orderBean" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
The orderBean type definition illustrated in Listing 7 maps to the OrderBean class. The
orderBean type definition is comprised of:
A customer element whose type is customer.
An orderId whose type is string.
orderItems (which is an array, because it specifies the maxOccurs attribute as
unbounded) whose type is orderItem.
shippingAddress whose type is address.
Listing 7. Schema declaration for processOrder
<xs:complexType name="orderBean">
<xs:sequence>
<xs:element name="customer" type="tns:customer" minOccurs="0" />
<xs:element name="orderId" type="xs:string" minOccurs="0" />
<xs:element nillable="true" maxOccurs="unbounded" name="orderItems"
type="tns:orderItem" minOccurs="0" />
<xs:element name="shippingAddress" type="tns:address"
minOccurs="0" />
</xs:sequence>
</xs:complexType
Similarly, the rest of the schema definitions for customer, orderItems, and address
are mapped to the Customer, OrderItem, and Address Java beans, respectively.
Design and develop JAX-WS 2.0 web services
Page 8 of 16
ibm.com/developerWorks/
developerWorks
With the schema definitions analyzed, let's revisit the message definitions
in WSDL, which are shown in Listing 8. The WSDL specifies the messages
processOrder and processOrderResponse whose part elements are processOrder and
processOrderResponse (you've already seen their schema definitions). The portType
specifies the operation processOrder whose input message is processOrder and
whose output message is processOrderResponse.
Listing 8. processOrder message element in WSDL document
<message name="processOrder">
<part element="tns:processOrder" name="parameters" />
</message>
<message name="processOrderResponse">
<part element="tns:processOrderResponse" name="parameters" />
</message>
<portType name="OrderProcessService">
<operation name="processOrder">
<input message="tns:processOrder" />
<output message="tns:processOrderResponse" />
</operation>
</portType>
Next, the WSDL bindings are defined. This defines the soap:binding style as
document and the soap:body use tag as literal for input and output message
formats for the operation processOrder. The generated WSDL definitions map to the
@SOAPBinding annotation that you defined on the OrderProcessService class (see
Listing 9).
Listing 9. Binding information for WSDL document
<binding name="OrderProcessPortBinding" type="tns:OrderProcessService">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="processOrder">
<soap:operation soapAction="" />
<input>
<soap:body use="literal" />
</input>
<output>
<soap:body use="literal" />
</output>
</operation>
</binding>
Next, the WSDL services are defined. These specify the port and corresponding
binding type, along with the actual location of the service. This is typically an HTTP
location, which in this case is http://localhost:8080/OrderProcessWeb/orderprocess.
You can see this in detail in Listing 10.
Listing 10. Service information for WSDL document
<service name="OrderProcess">
<port name="OrderProcessPort" binding="tns:OrderProcessPortBinding">
<soap:address location="http://localhost:8080/OrderProcessWeb/orderprocess" />
</port>
Page 9 of 16
developerWorks
ibm.com/developerWorks/
With this you've analyzed the generated WSDL and schema artifacts. Listing 11
illustrates a sample SOAP request message sent by the web service client when it
invokes the processOrder operation.
Listing 11. Sample SOAP message for processOrder operation
<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1=" http://jawxs.ibm.tutorial/jaxws/orderprocess"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soapenv:Body>
<ns1:processOrder>
<arg0>
<customer><customerId>A123</customerId>
<firstName>John</firstName><lastName>Smith</lastName></customer>
<orderItems><itemId>11</itemId><qty>11</qty></orderItems>
</arg0>
</ns1:processOrder>
</soapenv:Body>
</soapenv:Envelope>
SEI
Service (the service implementation class you need to implement)
JAXB-generated classes from schema types
Exception class mapped from wsdl:fault (if any)
Clients use the artifacts generated to invoke the web service. The web service clients
don't need to deal with any SOAP format, like creating or parsing SOAP messages.
Rather, this is handled by the JAX-WS run time, which uses the generated artifact
code (the JAXB-generated class). The web service client in turn deals with the Java
object (the JAXB-generated class), which eases the development of web service
clients and invoking operations on the web service.
You generate JAX-WS artifacts from the OrderProcess WSDL using the wsimport
tool. Then you create a web service client, which uses generated artifact code to
invoke the order-processing web service. To generate the JAX-WS artifacts, navigate
to the JAXWS-Tutorial directory, and run the wsimport command shown in Listing 12.
Before doing this, though, make sure you've published the web service by running
OrderWebServicePublisher as pointed out in step 5 in the Generate JAX-WS artifacts
section.
Design and develop JAX-WS 2.0 web services
Page 10 of 16
ibm.com/developerWorks/
developerWorks
Listing 12. wsimport command for generating JAX-WS artifacts used by web
service client
wsimport -keep -p com.ibm.jaxws.tutorial.service.client
http://localhost:8080/OrderProcessWeb/orderprocess?wsdl
The -keep option indicates that you keep the generated files, and the -p option
specifies the package name where the artifact needs to be generated. http://
localhost:8080/OrderProcessWeb/orderprocess?wsdl specifies the location of the
WSDL file. The following artifacts are generated from the OrderProcessService
WSDL:
JAXB classes (Address, Customer, OrderBean, and OrderItem): Generated by
reading the schema definitions defined in the OrderProcessService WSDL
RequestWrapper and ResponseWrapper classes (ProcessOrder and
ProcessOrderResponse): Wrap the input and output for document literal-wrapped
style
Service class (OrderProcess): The class that your clients use to make requests
to the web service
Service interface (OrderProcessService): Class contains the interface, which
your service implements
Now take a look at how to create a web service client using the artifacts you
generated above. A sample reference code is provided in the com\ibm\jaxws\tutorial
\service\client folder. The code for the web service client is provided in Listing 13.
Listing 13. Code listing for order-processing web service client
package com.ibm.jaxws.tutorial.service.client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
public class OrderClient {
final QName qName = new QName(
"http://jawxs.ibm.tutorial/jaxws/orderprocess", "OrderProcess");
public static void main(String[] args) {
if (args.length != 1) {
System.out
.println("Specify the URL of the OrderProcess Web Service");
System.exit(-1);
}
URL url = getWSDLURL(args[0]);
OrderClient client = new OrderClient();
client.processOrder(url);
}
private static URL getWSDLURL(String urlStr) {
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
Page 11 of 16
developerWorks
ibm.com/developerWorks/
Page 12 of 16
ibm.com/developerWorks/
developerWorks
javac com\ibm\jaxws\tutorial\service\client\OrderClient.java
Execute the web service client by providing the WSDL URL for the order process
web service using this command:
java com.ibm.jaxws.tutorial.service.client.OrderClient http://
localhost:8080/OrderProcessWeb/orderprocess?wsdl
When the web service client is executed, you'll see the following output at the
console, where OrderWebServicePublisher is running:
processOrder called for customer A123
Number of items is 1
At the console where the web service client is executed, you get the following output:
Order id is A1234
As you see in the client code, you don't deal with any SOAP or XML-based format for
invoking web service operations; instead you deal with generated JAXB classes for
input and output messages and use the service interface and service class objects,
which act as stubs for web service invocation. The stubs are responsible for creating
SOAP requests from JAXB annotations and converting the SOAP response back to
the Java object.
You have now successfully created and published your web service and executed it
via a web service client!
Section 7. Summary
In this tutorial, you learned how to design and develop web services using the codefirst development approach and JAX-WS technology. JAX-WS is a great choice
because it provides a complete web services stack to simplify the development and
deployment of web services.
The order-processing web service you developed in this tutorial uses the documentstyle web service, which ensures that the service consumer and service provider
communicate using XML documents. The XML documents adhere to well-defined
contracts, typically created using XML Schema definitions. The XML Schema format
specifies the contract of the business messages that service consumers can call,
and adheres it. Document-style web services should be the preferred approach of
developing enterprise web services.
Page 13 of 16
developerWorks
ibm.com/developerWorks/
Downloads
Description
Name
Size
Download
method
jaxws.zip
32KB
HTTP
Page 14 of 16
ibm.com/developerWorks/
developerWorks
Resources
Learn
Read the Hands on web services book for comprehensive hands-on
information about how to design and develop real-world web services
applications.
Check out the article "web services architecture using MVC
style" (developerWorks, February 2002) to learn how the MVC architecture can
be applied to invoke static or dynamic web services.
The SOA and web services zone on IBM developerWorks hosts hundreds of
informative articles and introductory, intermediate, and advanced tutorials on
how to develop web services applications.
The IBM SOA Web site offers an overview of SOA and how IBM can help you
get there.
Stay current with developerWorks technical events and webcasts. Check out
the following SOA and web services tech briefings in particular:
Get started on SOA with WebSphere's proven, flexible entry points
Building SOA solutions and managing the service lifecycle
SCA/SDO: To drive the next generation of SOA
SOA reuse and connectivity
Browse for books on these and other technical topics at the Safari bookstore.
Check out a quick web services on demand demo.
Get products and technologies
Innovate your next development project with IBM trial software, available for
download or on DVD.
Discuss
Participate in the discussion forum for this content.
Get involved in the developerWorks community by participating in
developerWorks blogs, including the following SOA and web services-related
blogs:
Service Oriented Architecture -- Off the Record with Sandy Carter
Best Practices in Service-Oriented Architecture with Ali Arsanjani
WebSphere SOA and J2EE in Practice with Bobby Woolf
Building SOA applications with patterns with Dr. Eoin Lane
Client Insights, Concerns and Perspectives on SOA with Kerrie Holley
Service-Oriented Architecture and Business-Level Tooling with Simon
Johnston
SOA, ESB and Beyond with Sanjay Bose
SOA, Innovations, Technologies, Trends...and a little fun with Mark Colan
Page 15 of 16
developerWorks
ibm.com/developerWorks/
Rajeev Hathi
Rajeev Hathi has been working as a software consultant for the J2EE
platform. His interests are architecting and designing J2EE-based
applications. His favorite subject is Web services, through which he likes
to apply and impart SOA concepts. His hobbies are watching sports and
listening to rock music.
Copyright IBM Corporation 2007
(www.ibm.com/legal/copytrade.shtml)
Trademarks
(www.ibm.com/developerworks/ibm/trademarks/)
Page 16 of 16