SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Using Java to implement SOAP
web Services: JAX-WS

Web Technology
2II25
Dr. Katrien Verbert
Dr. ir. Natasha Stash
Dr. George Fletcher
JAX-WS 2.0

• Part of Java EE
• New in Java SE 6
• API stack for web services.
• New API’s:
   • JAX-WS, SAAJ, Web Service metadata
• New packages:
   • javax.xml.ws, javax.xml.soap, javax.jws
Communication between JAX-WS Web Service
and Client
Java Web Services Basics
Writing a webservice
package loanservice;


import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.Endpoint;


@WebService
public class LoanApprover {


    @WebMethod
    public boolean approve(String name) {
        return name.equals("Mike");
    }
}
Annotations
Annotations are a new feature of JDK 1.5 and later.
   • Essentially they are markers in the Java source code
   • That can be used by external tools to generate code
Format looks like
   @ThisIsAnAnnotation(foo=“bar”)
Annotations can occur only in specific places in the code
   • before a class definition,
   • before a method declaration, ...
Requirements of a JAX-WS Endpoint

• The implementing class must be annotated with the @WebService or
@WebServiceProvider annotation
• The business methods of the implementing class must be public.
• The business methods must not be declared static or final.
• Business methods that are exposed to web service clients must be annotated
with @WebMethod.
• Business methods that are exposed to web service clients must have JAXB-
compatible parameters and return types.
    • See the list of JAXB default data type bindings at
    • http://docs.oracle.com/javaee/5/tutorial/doc/bnazq.html#bnazs.
@WebService annotation

• Indicates that a class represents a web service
• Optional element name
   • specifies the name of the proxy class that will be generated for
   the client
• Optional element serviceName
   • specifies the name of the class to obtain a proxy object.
Creating, Publishing, Testing and Describing a
Web Service
Calculator web service
• Provides method that takes two integers
• Can determine their sum
CalculatorWS example

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;


@WebService(serviceName = "CalculatorWS")
                                                             Declare that method add is
public class CalculatorWS {                                  a WebMethod

                                                             Specify parameter names
    @WebMethod
    public int add (@WebParam (name= "value1") int value1,
     @WebParam( name="value2" ) int value2){
        return value1 + value2;
    }
}
Coding the Service Endpoint Implementation
Class

• @WebService annotation at the beginning of each new
web service class you create
• @WebMethod annotation at the beginning of each
method that is exposed as a WSDL operation
   • Methods that are tagged with the @WebMethod annotation
   can be called remotely
   • Methods that are not tagged with @WebMethod are not
   accessible to clients that consume the web service
• @WebParam annotation is used here to control the
name of a parameter in the WSDL
   • Without this annotation the parameter name = arg0
• @WebMethod annotation
   - Optional operationName element to specify the method
   name that is exposed to the web service’s client
• Parameters of web methods are annotated with the
@WebParam annotation
   - Optional element name indicates the parameter name that
   is exposed to the web service’s clients
Building, Packaging, and Deploying the Service


Java IDEs
•   Netbeans
    • download: http://netbeans.org/
    • tutorial: http://netbeans.org/kb/docs/websvc/jax-ws.html?print=yes
•   Eclipse
    • download: http://www.eclipse.org/
    • tutorial:
    http://rantincsharp.wordpress.com/2008/10/14/a-simple-soap-web-service-examp
•   IntelliJ IDEA
    • download: http://www.jetbrains.com/idea/
    • tutorial:
    http://wiki.jetbrains.net/intellij/Web_Services_with_IntelliJ_IDEA#JAX_WS
Using Ant
http://docs.oracle.com/javaee/6/tutorial/doc/bnayn.html
Netbeans




http://netbeans.org/downloads/
Creating a Web Application Project and Adding a
Web Service Class in Netbeans
• In Netbeans, you focus on the logic of the web service
and let the IDE handle the web service’s infrastructure
• To create a web service in Netbeans
   • Create a project of type Web Application
   • The IDE generates additional files that support the web
   application
Publishing the HugeInteger Web Service from
Netbeans
• Netbeans handles all details of building and deploying a web service
• To build project
    • Right click the project name in the Netbeans Projects tab
    • Select Build Project
• To deploy
    • Select Deploy Project
    • Deploys to the server you selected during application setup
    • Also builds the project if it has changed and starts the application server
    if it is not already running
• To Execute
    • Select Run Project
    • Also builds the project if it has changed and starts the application server
    if it is not already running
Publishing the Calculator Web Service from
Netbeans
Testing the Calculator Web Service with Sun Java
System Application Server’s Tester Web page
• Sun Java System Application Server
   • can dynamically create a Tester web page
   • for testing a web service’s methods from a web browser
•To display the Tester web page
   • select your web service Test Web Service
   • type web service’s URL in browser followed by ?Tester
Testing the Calculator Web Service with Sun Java
System Application Server’s Tester Web page
Tester
Describing a Web Service with the Web Service
 Description Language (WSDL)
• To consume a web service
   • Must know where to find the web service
   • Must be provided with the web service’s description
• Web Service Description Language (WSDL)
   • Describe web services in a platform-independent manner
   • The server generates a WSDL dynamically for you
   • Client tools parse the WSDL to create the client-side proxy class that
   accesses the web service
•To view the WSDL for a web service
   • Type URL in the browser’s address field followed by ?WSDL or
   • Click the WSDL File link in the Sun Java System Application Server’s Tester
   web page
Example WSDL
Creating a Client in Netbeans to Consume a Web
 Service
• When you add a web service reference
   • IDE creates and compiles the client-side artifacts
   • the framework of Java code that supports the client-side proxy
   class
• Client calls methods on a proxy object
   • Proxy uses client-side artifacts to interact with the web service
• To add a web service reference
   • Right click the client project name in the Netbeans Projects tab
   • Select New > Web Service Client…
   • Specify the URL of the web service’s WSDL in the dialog’s
   WSDL URL field
Calculator client
import calculator.*;


public class CalculatorClient {
    public static void main(String[] args) {
        CalculatorWS_Service service=new CalculatorWS_Service();
        CalculatorWS port= service.getCalculatorWSPort();
        int result = port.add(2, 3);
        System.out.println(result);
    }
}
Relevant links

• Netbeans tutorial for developing a SOAP-based web services:
  http://netbeans.org/kb/docs/websvc/jax-ws.html
• Building SOAP-based web services with JAX-WS:
  http://docs.oracle.com/javaee/6/tutorial/ doc/bnayl.html
SOAP and XML processing

Web Technology
2II25

Dr. Katrien Verbert
Dr. ir. Natasha Stash
Dr. George Fletcher
XML document

<?xml version="1.0"?>
   <Order>
        <Date>2003/07/04</Date>
        <CustomerId>123</CustomerId>
        <CustomerName>Acme Alpha</CustomerName>
        <Item>
             <ItemId> 987</ItemId>
             <ItemName>Coupler</ItemName>
             <Quantity>5</Quantity>
        </Item>
        <Item>
             <ItemId>654</ItemId>
             <ItemName>Connector</ItemName>
             <Quantity unit="12">3</Quantity>
        </Item>
  </Order>
Parsing XML

Goal
   Read XML files into data structures in programming languages


Possible strategies
   • Parse into generic tree structure (DOM)
   • Parse as sequence of events (SAX)
   • Automatically parse to language-specific objects (JAXB)
JAXB

JAXB: Java API for XML Bindings

Defines an API for automatically representing XML schema
  as collections of Java classes.

Most convenient for application programming
Annotations markup

@XmlAttribute to designate a field as an attribute
@XmlRootElement to designate the document root element.
@XmlElement to designate a field as a node element
@XmlElementWrapper to specify the element that encloses a
 repeating series of elements



Note that you should specify only the getter method as @XmlAttribute
   or @XmlElement.
Jaxb oddly treats both the field and the getter method as independent
   entities
Order example

import javax.xml.bind.annotation.*;


@XmlRootElement
public class Item {


    @XmlElement
    private String itemId;
    @XmlElement
    private String ItemName;
    @XmlElement
    private int quantity;


    public Item() {
    }
}
Order example
import javax.xml.bind.annotation.*;
import java.util.*;


@XmlRootElement
public class Order {


  @XmlElement
  private String date;
  @XmlElement
  private String customerId;
  @XmlElement
  private String customerName;
  @XmlElement
  private List<Item> items;


  public Order() {
      this.items=new ArrayList<Item>();
  }
Marshalling
marshalling
   the process of producing an XML document from Java objects
unmarshalling
   the process of producing a content tree from an XML document


JAXB only allows you to unmarshal valid XML documents
JAXB only allows you to marshal valid content trees into XML
Marshalling example

public String toXmlString(){
     try{
         JAXBContext context=JAXBContext.newInstance(Order.class);
         Marshaller m = context.createMarshaller();
         m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
         ByteArrayOutputStream b=new ByteArrayOutputStream();
         m.marshal(this,b);
         return b.toString();
     }catch (Exception e){
         e.printStackTrace();
         return null;
     }
}
Unmarshalling example

public Order fromXmlString(String s){
     try{
         JAXBContext jaxbContext = JAXBContext.newInstance(Order.class);
         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller()
         Order order = (Order) jaxbUnmarshaller.unmarshal(new StreamSource( new
         StringReader(s)));
         return order;
     }catch (Exception e){
         e.printStackTrace();
         return null;
     }
}
Test transformation

public static void main(String args[]){
      Order o=new Order("1 March 2013", "123", "Katrien");
      o.getItems().add(new Item("1", "iPhone 5", 2));
      o.getItems().add(new Item("2", "Nokia Lumia 800", 2));
      System.out.println(o.toXmlString());


  }
Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order>
  <customerId>123</customerId>
  <customerName>Katrien Verbert</customerName>
  <date>12 February 2013</date>
  <items>
    <itemId>id1</itemId>
    <ItemName>Iphone 5</ItemName>
    <quantity>2</quantity>
  </items>
  <items>
    <itemId>id2</itemId>
    <ItemName>Nokia Lumia 800</ItemName>
    <quantity>1</quantity>
  </items>
</order>
k.verbert@tue.nl
n.v.stash@tue.nl
g.h.l.fletcher@tue.nl




          03/28/11

Weitere ähnliche Inhalte

Was ist angesagt?

Web Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NETWeb Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NET
Ponraj
 

Was ist angesagt? (20)

Web Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NETWeb Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NET
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
Express JS
Express JSExpress JS
Express JS
 
Express JS
Express JSExpress JS
Express JS
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
 
Express js
Express jsExpress js
Express js
 
1. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES61. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES6
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 

Andere mochten auch

Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overview
Raveendra Bhat
 

Andere mochten auch (17)

Java web services using JAX-WS
Java web services using JAX-WSJava web services using JAX-WS
Java web services using JAX-WS
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Web Services
Web ServicesWeb Services
Web Services
 
Web Service Presentation
Web Service PresentationWeb Service Presentation
Web Service Presentation
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
 
WebLogic in Practice: SSL Configuration
WebLogic in Practice: SSL ConfigurationWebLogic in Practice: SSL Configuration
WebLogic in Practice: SSL Configuration
 
Implementing Web Services In Java
Implementing Web Services In JavaImplementing Web Services In Java
Implementing Web Services In Java
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
 
Primavera integration possibilities Technical overview - Oracle Primavera Col...
Primavera integration possibilities Technical overview - Oracle Primavera Col...Primavera integration possibilities Technical overview - Oracle Primavera Col...
Primavera integration possibilities Technical overview - Oracle Primavera Col...
 
WebLogic Deployment Plan Example
WebLogic Deployment Plan ExampleWebLogic Deployment Plan Example
WebLogic Deployment Plan Example
 
Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overview
 
Learn Oracle WebLogic Server 12c Administration
Learn Oracle WebLogic Server 12c AdministrationLearn Oracle WebLogic Server 12c Administration
Learn Oracle WebLogic Server 12c Administration
 
Oracle Web Logic server
Oracle Web Logic serverOracle Web Logic server
Oracle Web Logic server
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencast
 
Where and when to use the Oracle Service Bus (OSB)
Where and when to use the Oracle Service Bus (OSB)Where and when to use the Oracle Service Bus (OSB)
Where and when to use the Oracle Service Bus (OSB)
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 

Ähnlich wie Using Java to implement SOAP Web Services: JAX-WS

Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
Chui-Wen Chiu
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
SPTechCon
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascript
DsixE Inc
 

Ähnlich wie Using Java to implement SOAP Web Services: JAX-WS (20)

Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
 
Intro to .NET for Government Developers
Intro to .NET for Government DevelopersIntro to .NET for Government Developers
Intro to .NET for Government Developers
 
Dwr
DwrDwr
Dwr
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
SynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax DevelopmentSynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax Development
 
SCDJWS 5. JAX-WS
SCDJWS 5. JAX-WSSCDJWS 5. JAX-WS
SCDJWS 5. JAX-WS
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
 
Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
Web services intro.
Web services intro.Web services intro.
Web services intro.
 
VMworld 2013: vSphere UI Platform Best Practices: Putting the Web Client SDK ...
VMworld 2013: vSphere UI Platform Best Practices: Putting the Web Client SDK ...VMworld 2013: vSphere UI Platform Best Practices: Putting the Web Client SDK ...
VMworld 2013: vSphere UI Platform Best Practices: Putting the Web Client SDK ...
 
Jax Ws2.0
Jax Ws2.0Jax Ws2.0
Jax Ws2.0
 
Ajax toolkit-framework
Ajax toolkit-frameworkAjax toolkit-framework
Ajax toolkit-framework
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascript
 
Tutorial, Part 4: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 4: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 4: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 4: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Welcome to Web Services
Welcome to Web ServicesWelcome to Web Services
Welcome to Web Services
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 

Mehr von Katrien Verbert

Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...
Katrien Verbert
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Katrien Verbert
 

Mehr von Katrien Verbert (20)

Explainability methods
Explainability methodsExplainability methods
Explainability methods
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?
 
Explaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveExplaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspective
 
Explaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedExplaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learned
 
Designing Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedDesigning Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons Learned
 
Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...
 
Explainable AI for non-expert users
Explainable AI for non-expert usersExplainable AI for non-expert users
Explainable AI for non-expert users
 
Towards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsTowards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methods
 
Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
 
Learning analytics for feedback at scale
Learning analytics for feedback at scaleLearning analytics for feedback at scale
Learning analytics for feedback at scale
 
Interactive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningInteractive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learning
 
Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”
 
Interactive Recommender Systems
Interactive Recommender SystemsInteractive Recommender Systems
Interactive Recommender Systems
 
Web Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLWeb Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTML
 
Information Visualisation: perception and principles
Information Visualisation: perception and principlesInformation Visualisation: perception and principles
Information Visualisation: perception and principles
 
Web Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionWeb Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: Introduction
 
Information Visualisation: Introduction
Information Visualisation: IntroductionInformation Visualisation: Introduction
Information Visualisation: Introduction
 

Using Java to implement SOAP Web Services: JAX-WS

  • 1. Using Java to implement SOAP web Services: JAX-WS Web Technology 2II25 Dr. Katrien Verbert Dr. ir. Natasha Stash Dr. George Fletcher
  • 2. JAX-WS 2.0 • Part of Java EE • New in Java SE 6 • API stack for web services. • New API’s: • JAX-WS, SAAJ, Web Service metadata • New packages: • javax.xml.ws, javax.xml.soap, javax.jws
  • 3. Communication between JAX-WS Web Service and Client
  • 5. Writing a webservice package loanservice; import javax.jws.WebService; import javax.jws.WebMethod; import javax.xml.ws.Endpoint; @WebService public class LoanApprover { @WebMethod public boolean approve(String name) { return name.equals("Mike"); } }
  • 6. Annotations Annotations are a new feature of JDK 1.5 and later. • Essentially they are markers in the Java source code • That can be used by external tools to generate code Format looks like @ThisIsAnAnnotation(foo=“bar”) Annotations can occur only in specific places in the code • before a class definition, • before a method declaration, ...
  • 7. Requirements of a JAX-WS Endpoint • The implementing class must be annotated with the @WebService or @WebServiceProvider annotation • The business methods of the implementing class must be public. • The business methods must not be declared static or final. • Business methods that are exposed to web service clients must be annotated with @WebMethod. • Business methods that are exposed to web service clients must have JAXB- compatible parameters and return types. • See the list of JAXB default data type bindings at • http://docs.oracle.com/javaee/5/tutorial/doc/bnazq.html#bnazs.
  • 8. @WebService annotation • Indicates that a class represents a web service • Optional element name • specifies the name of the proxy class that will be generated for the client • Optional element serviceName • specifies the name of the class to obtain a proxy object.
  • 9. Creating, Publishing, Testing and Describing a Web Service Calculator web service • Provides method that takes two integers • Can determine their sum
  • 10. CalculatorWS example import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; @WebService(serviceName = "CalculatorWS") Declare that method add is public class CalculatorWS { a WebMethod Specify parameter names @WebMethod public int add (@WebParam (name= "value1") int value1, @WebParam( name="value2" ) int value2){ return value1 + value2; } }
  • 11. Coding the Service Endpoint Implementation Class • @WebService annotation at the beginning of each new web service class you create • @WebMethod annotation at the beginning of each method that is exposed as a WSDL operation • Methods that are tagged with the @WebMethod annotation can be called remotely • Methods that are not tagged with @WebMethod are not accessible to clients that consume the web service • @WebParam annotation is used here to control the name of a parameter in the WSDL • Without this annotation the parameter name = arg0
  • 12. • @WebMethod annotation - Optional operationName element to specify the method name that is exposed to the web service’s client • Parameters of web methods are annotated with the @WebParam annotation - Optional element name indicates the parameter name that is exposed to the web service’s clients
  • 13. Building, Packaging, and Deploying the Service Java IDEs • Netbeans • download: http://netbeans.org/ • tutorial: http://netbeans.org/kb/docs/websvc/jax-ws.html?print=yes • Eclipse • download: http://www.eclipse.org/ • tutorial: http://rantincsharp.wordpress.com/2008/10/14/a-simple-soap-web-service-examp • IntelliJ IDEA • download: http://www.jetbrains.com/idea/ • tutorial: http://wiki.jetbrains.net/intellij/Web_Services_with_IntelliJ_IDEA#JAX_WS Using Ant http://docs.oracle.com/javaee/6/tutorial/doc/bnayn.html
  • 15. Creating a Web Application Project and Adding a Web Service Class in Netbeans • In Netbeans, you focus on the logic of the web service and let the IDE handle the web service’s infrastructure • To create a web service in Netbeans • Create a project of type Web Application • The IDE generates additional files that support the web application
  • 16. Publishing the HugeInteger Web Service from Netbeans • Netbeans handles all details of building and deploying a web service • To build project • Right click the project name in the Netbeans Projects tab • Select Build Project • To deploy • Select Deploy Project • Deploys to the server you selected during application setup • Also builds the project if it has changed and starts the application server if it is not already running • To Execute • Select Run Project • Also builds the project if it has changed and starts the application server if it is not already running
  • 17. Publishing the Calculator Web Service from Netbeans
  • 18. Testing the Calculator Web Service with Sun Java System Application Server’s Tester Web page • Sun Java System Application Server • can dynamically create a Tester web page • for testing a web service’s methods from a web browser •To display the Tester web page • select your web service Test Web Service • type web service’s URL in browser followed by ?Tester
  • 19. Testing the Calculator Web Service with Sun Java System Application Server’s Tester Web page
  • 21. Describing a Web Service with the Web Service Description Language (WSDL) • To consume a web service • Must know where to find the web service • Must be provided with the web service’s description • Web Service Description Language (WSDL) • Describe web services in a platform-independent manner • The server generates a WSDL dynamically for you • Client tools parse the WSDL to create the client-side proxy class that accesses the web service •To view the WSDL for a web service • Type URL in the browser’s address field followed by ?WSDL or • Click the WSDL File link in the Sun Java System Application Server’s Tester web page
  • 23. Creating a Client in Netbeans to Consume a Web Service • When you add a web service reference • IDE creates and compiles the client-side artifacts • the framework of Java code that supports the client-side proxy class • Client calls methods on a proxy object • Proxy uses client-side artifacts to interact with the web service • To add a web service reference • Right click the client project name in the Netbeans Projects tab • Select New > Web Service Client… • Specify the URL of the web service’s WSDL in the dialog’s WSDL URL field
  • 24. Calculator client import calculator.*; public class CalculatorClient { public static void main(String[] args) { CalculatorWS_Service service=new CalculatorWS_Service(); CalculatorWS port= service.getCalculatorWSPort(); int result = port.add(2, 3); System.out.println(result); } }
  • 25. Relevant links • Netbeans tutorial for developing a SOAP-based web services: http://netbeans.org/kb/docs/websvc/jax-ws.html • Building SOAP-based web services with JAX-WS: http://docs.oracle.com/javaee/6/tutorial/ doc/bnayl.html
  • 26. SOAP and XML processing Web Technology 2II25 Dr. Katrien Verbert Dr. ir. Natasha Stash Dr. George Fletcher
  • 27. XML document <?xml version="1.0"?> <Order> <Date>2003/07/04</Date> <CustomerId>123</CustomerId> <CustomerName>Acme Alpha</CustomerName> <Item> <ItemId> 987</ItemId> <ItemName>Coupler</ItemName> <Quantity>5</Quantity> </Item> <Item> <ItemId>654</ItemId> <ItemName>Connector</ItemName> <Quantity unit="12">3</Quantity> </Item> </Order>
  • 28. Parsing XML Goal Read XML files into data structures in programming languages Possible strategies • Parse into generic tree structure (DOM) • Parse as sequence of events (SAX) • Automatically parse to language-specific objects (JAXB)
  • 29. JAXB JAXB: Java API for XML Bindings Defines an API for automatically representing XML schema as collections of Java classes. Most convenient for application programming
  • 30. Annotations markup @XmlAttribute to designate a field as an attribute @XmlRootElement to designate the document root element. @XmlElement to designate a field as a node element @XmlElementWrapper to specify the element that encloses a repeating series of elements Note that you should specify only the getter method as @XmlAttribute or @XmlElement. Jaxb oddly treats both the field and the getter method as independent entities
  • 31. Order example import javax.xml.bind.annotation.*; @XmlRootElement public class Item { @XmlElement private String itemId; @XmlElement private String ItemName; @XmlElement private int quantity; public Item() { } }
  • 32. Order example import javax.xml.bind.annotation.*; import java.util.*; @XmlRootElement public class Order { @XmlElement private String date; @XmlElement private String customerId; @XmlElement private String customerName; @XmlElement private List<Item> items; public Order() { this.items=new ArrayList<Item>(); }
  • 33. Marshalling marshalling the process of producing an XML document from Java objects unmarshalling the process of producing a content tree from an XML document JAXB only allows you to unmarshal valid XML documents JAXB only allows you to marshal valid content trees into XML
  • 34. Marshalling example public String toXmlString(){ try{ JAXBContext context=JAXBContext.newInstance(Order.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); ByteArrayOutputStream b=new ByteArrayOutputStream(); m.marshal(this,b); return b.toString(); }catch (Exception e){ e.printStackTrace(); return null; } }
  • 35. Unmarshalling example public Order fromXmlString(String s){ try{ JAXBContext jaxbContext = JAXBContext.newInstance(Order.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller() Order order = (Order) jaxbUnmarshaller.unmarshal(new StreamSource( new StringReader(s))); return order; }catch (Exception e){ e.printStackTrace(); return null; } }
  • 36. Test transformation public static void main(String args[]){ Order o=new Order("1 March 2013", "123", "Katrien"); o.getItems().add(new Item("1", "iPhone 5", 2)); o.getItems().add(new Item("2", "Nokia Lumia 800", 2)); System.out.println(o.toXmlString()); }
  • 37. Output <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <order> <customerId>123</customerId> <customerName>Katrien Verbert</customerName> <date>12 February 2013</date> <items> <itemId>id1</itemId> <ItemName>Iphone 5</ItemName> <quantity>2</quantity> </items> <items> <itemId>id2</itemId> <ItemName>Nokia Lumia 800</ItemName> <quantity>1</quantity> </items> </order>

Hinweis der Redaktion

  1. An application that consumes a web service consists of two parts An object of a proxy class for interacting with the web service A client application that consumes the web service by invoking methods on the proxy object The proxy object handles the details of communicating with the web service on the client ’ s behalf JAX-WS 2.0 Requests to and responses from web services are typically transmitted via SOAP Any client capable of generating and processing SOAP messages can interact with a web service, regardless of the language in which the web service is written
  2. The starting point for developing a JAX-WS web service is a Java class annotated with the javax.jws.WebService annotation. The @WebService annotation defines the class as a web service endpoint.
  3. always add a default constructor