Developing JAX-WS Web Service Clients

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.

In this tutorial, you use the web service facilities provided by NetBeans IDE to analyze a Spell Checker web service, after which you build a web client that interacts with the service. The client uses a servlet class and a web page. The user passes information to the servlet from the web page.

netbeans stamp 80 74 73
Figure 1. Content on this page applies to the NetBeans IDE 7.2, 7.3, 7.4 and 8.0

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

NetBeans IDE

Java EE download bundle

Java Development Kit (JDK)

version 7 or version 8

Java EE-compliant web or application server

Tomcat web server 7.x or 8.x GlassFish Server Open Source Edition Oracle WebLogic Server

Important: You need to enable access to external schema to create the web service client. For more details, see the FAQ How to enable parsing of WSDL with an external schema?

Note. Both Tomcat and the GlassFish server can be installed with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit the the GlassFish server downloads page or the Apache Tomcat downloads page.

This is what your client will look like, with all data received from the web service:

jaxwsc spellchecker report
Figure 2. Spell Checker report

By the end of this tutorial, you will discover that your only contribution to the application consists of providing the text to be checked, invoking an operation on the web service, and rendering the result. The IDE generates all the code needed for contacting the web service and sending the text. The spell checker web service takes care of the rest. It identifies the misspelled words and provides a list of suggested alternatives.

The spell checker web service used in this tutorial is provided by the CDYNE Corporation. CDYNE develops, markets and supports a comprehensive suite of data enhancement, data quality and data analysis web services and business intelligence integration. The spell checker web service is one of the web services provided by CDYNE. Note that the strength of an application based on one or more web services depends on the availability and reliability of the web services. However, CDYNE’s FAQ points out that it has a "100% availability objective" and that in the event of "natural disaster, act of terror, or other catastrophe, web service traffic is transferred to our secondary data center". NetBeans thanks CDYNE for enabling this tutorial to be written and for supporting its development.

Consuming the Spell Checker Web Service

To use a web service over a network, which is called "consuming" a web service, you need to create a web service client. For the creation of web service clients, NetBeans IDE provides a client creation facility, which is the Web Service Client wizard that generates code for looking up a web service. It also provides facilities for developing the created web service client, a work area consisting of nodes in the Projects window. These facilities are part of the EE bundle of the NetBeans IDE installation. They are available straight out of the box and no plug-ins are needed.

Creating the Client

In this section, you use a wizard to generate Java objects from the web service’s WSDL file.

  1. Choose File > New Project (Ctrl-Shift-N on Windows and Linux, ⌘-Shift-N on MacOS). Under Categories, choose Java Web. Under Projects, choose Web Application. Click Next. Name the project SpellCheckService and make sure that you specify an appropriate server as your target server. (Refer to the "Getting Started" section for details.) Leave all other options at default and click Finish.

  2. In the Projects window, right-click the SpellCheckService project node and choose New > Other and select Web Service Client in the Web Services category in the New File wizard. Click Next.

  3. Select WSDL URL and specify the following URL for the web service:

If you are behind a firewall, you might need to specify a proxy server—otherwise the WSDL file cannot be downloaded. To specify the proxy server, click Set Proxy in the wizard. The IDE’s Options window opens, where you can set the proxy universally for the IDE.

  1. Leave the package name blank. By default the client class package name is taken from the WSDL. In this case is . Click Finish.

  1. In the Projects window, within the Web Service References node, you see the following:

ws refs
Figure 3. Projects window showing web service references

The Projects window shows that a web service called 'check' has made a number of 'CheckTextBody' and 'CheckTextBodyV2' operations available to your application. These operations check a string for spelling errors and returns data to be processed by the client. The V2 version of the service does not require authentication. You will use the checkSoap.CheckTextBodyV2 operation throughout this tutorial.

Within the Generated Sources node, you see the client stubs that were generated by the JAX-WS Web Service Client wizard.

gen files
Figure 4. Files view showing package structure of Build node

Expand the WEB-INF node and the wsdl subnode. You find a local copy of the WSDL file, named check.asmx.wsdl .

web inf

The URL of the WSDL that you used to create the client is mapped to the local copy of the WSDL in jax-ws-catalog.xml . Mapping to a local copy has several advantages. The remote copy of the WSDL does not have to be available for the client to run. The client is faster, because it does not need to parse a remote WSDL file. Lastly, portability is easier.

jax ws catalog

Developing the Client

There are many ways to implement a web service client. The web service’s WSDL file restricts the type of information that you can send to the web service, and it restricts the type of information you receive in return. However, the WSDL file lays no restrictions on how _ you pass the information it needs, nor on _what the user interface consists of. The client implementation you build below consists of a web page which allows the user to enter text to be checked and a servlet which passes the text to the web service and then produces a report containing the result.

Coding the Web Page

The web page will consist of a text area, where the user will enter text, and a button for sending the text to the web service. Depending on the version of the server that you chose as the target server, the IDE generated either index.html or index.jsp as the index page for the application.

  1. In the Projects window, expand the Web Pages node of the SpellCheckService project and double-click the index page ( index.html or index.jsp ) to open the file in the Source Editor.

  2. Copy the following code and paste it over the <body> tags in the index page:

  <form name="Test" method="post" action="SpellCheckServlet">
     <p>Enter the text you want to check:</p>
     <p><textarea rows="7" name="TextArea1" cols="40" ID="Textarea1"></textarea></p>
     <input type="submit" value="Spell Check" name="spellcheckbutton">

The previously listed code specifies that when the submit button is clicked, the content of the textarea is posted to a servlet called SpellCheckServlet .

Creating and Coding the Servlet

In this section you create a servlet that will interact with the web service. However, the code that performs the interaction will be provided by the IDE. As a result, you only need to deal with the business logic, that is, the preparation of the text to be sent and the processing of the result.

  1. Right-click the SpellCheckService project node in the Projects window, choose New > Other and then choose Web > Servlet. Click Next to open the New Servlet wizard.

  2. Name the servlet SpellCheckServlet and type clientservlet in the Package drop-down. Click Next.

name servlet
  1. In the Configure Servlet Deployment panel, note that the URL mapping for this servlet is /SpellCheckServlet . Accept the defaults and click Finish. The servlet opens in the Source Editor.

jaxwsc servlet
  1. Put your cursor inside the Source Editor, inside the processRequest method body of , and add some new lines right at the top of the method.

  1. Right-click in the space that you created in the previous step, and choose Insert Code > Call Web Service Operation. Click the checkSoap.CheckTextBodyV2 operation in the "Select Operation to Invoke" dialog box,as shown below:

insert ws ops
Figure 5. Projects window showing web service references

Click OK.

Note: You can also drag and drop the operation node directly from the Projects window into the editor, instead of calling up the dialog shown above.

At the end of the SpellCheckServlet class, you see a private method for calling the SpellCheckerV2 service and returning a object .

private DocumentSummary checkTextBodyV2(java.lang.String bodyText) { port = service.getCheckSoap();return port.checkTextBodyV2(bodyText);}

This method is all you need to invoke the operation on the web service. In addition, the following lines of code (in bold) are declared at the top of the class:

public class SpellCheckServlet extends HttpServlet {
    *@WebServiceRef(wsdlLocation = "")
    private Check service;*
  1. Replace the try block of the processRequest() method with the code that follows. The in-line comments throughout the code below explain the purpose of each line.

try (PrintWriter out = response.getWriter()) {
*    //Get the TextArea from the web page*String TextArea1 = request.getParameter("TextArea1");*//Initialize WS operation arguments*
    java.lang.String bodyText = TextArea1;

    *//Process result* doc = checkTextBodyV2(bodyText);
    String allcontent = doc.getBody();

    *//From the retrieved document summary,
    //identify the number of wrongly spelled words:*
    int no_of_mistakes = doc.getMisspelledWordCount();

    *//From the retrieved document summary,
    //identify the array of wrongly spelled words:*
    List allwrongwords = doc.getMisspelledWord();


    *//Display the report's name as a title in the browser's titlebar:*
    out.println("<title>Spell Checker Report</title>");

    *//Display the report's name as a header within the body of the report:*
    out.println("<h2><font color='red'>Spell Checker Report</font></h2>");

    *//Display all the content (correct as well as incorrectly spelled) between quotation marks:*
    out.println("<hr><b>Your text:</b> \"" + allcontent + "\"" + "<p>");

    *//For every array of wrong words (one array per wrong word),
    //identify the wrong word, the number of suggestions, and
    //the array of suggestions. Then display the wrong word and the number of suggestions and
    //then, for the array of suggestions belonging to the current wrong word, display each
    for (int i = 0; i < allwrongwords.size(); i++) {
        String onewrongword = ((Words) allwrongwords.get(i)).getWord();
        int onewordsuggestioncount = ((Words) allwrongwords.get(i)).getSuggestionCount();
        List allsuggestions = ((Words) allwrongwords.get(i)).getSuggestions();
        out.println("<hr><p><b>Wrong word:</b><font color='red'> " + onewrongword + "</font>");
        out.println("<p><b>" + onewordsuggestioncount + " suggestions:</b><br>");
        for (int k = 0; k < allsuggestions.size(); k++) {
            String onesuggestion = (String) allsuggestions.get(k);

    *//Display a line after each array of wrong words:*

    *//Summarize by providing the number of errors and display them:*
    out.println("<font color='red'><b>Summary:</b> " + no_of_mistakes + " mistakes (");
    for (int i = 0; i < allwrongwords.size(); i++) {
        String onewrongword = ((Words) allwrongwords.get(i)).getWord();


  1. You see a number of error bars and warning icons, indicating classes that are not found. To fix imports after pasting the code, either press Ctrl-Shift-I (⌘-Shift-I on Mac), or right-click anywhere, which opens a context menu, and select Fix Imports. (You have a choice of List classes to import. Accept the default java.util.List.) The full list of imported classes follows:

import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Note: *If you see warnings that the com.cdyne. classes cannot be found, do not be alarmed. This problem is resolved when you build the project, when the IDE parses the WSDL files and finds the classes.

Note that error handling has not been dealt with in the previously listed code. See Applying What You Have Learned for details.

Deploying the Client

The IDE uses an Ant build script to build and run your application. The IDE generates the build script based on the options you entered when creating the project. You can fine tune these options in the project’s Project Properties dialog box (right-click the project node in the Projects window and choose Properties).

  1. Right-click the project node and choose Run. After a while, the application deploys and displays the web page that you coded in the previous section.

  2. Enter some text, making sure that some of it is incorrectly spelled:

jaxwsc spellchecker form
Figure 6. JSP page with text to check
  1. Click Spell Check and see the result:

jaxwsc spellchecker report
Figure 7. Spell Checker report showing errors

Asynchronous Web Service Clients

By default, JAX-WS clients created by the NetBeans IDE are synchronous. Synchronous clients invoke a request on a service and then suspend their processing while they wait for a response. However, in some cases you want the client to continue with some other processing rather than wait for the response. For example, in some cases it may take a significant amount of time for the service to process the request. Web service clients that continue processing without waiting for the service response are called "asynchronous".

Asynchronous clients initiate a request to a service and then resume their processing without waiting for a response. The service handles the client request and returns a response at some later point, at which time the client retrieves the response and proceeds with its processing.

Asynchronous clients consume web services either through the "polling" approach or the "callback" approach. In the "polling" approach, you invoke a web service method and repeatedly ask for the result. Polling is a blocking operation because it blocks the calling thread, which is why you do not want to use it in a GUI application. In the "callback" approach you pass a callback handler during the web service method invocation. The handler’s handleResponse() method is called when the result is available. This approach is suitable to GUI applications because you do not have to wait for the response. For example, you make a call from a GUI event handler and return control immediately, keeping the user interface responsive. The drawback of the polling approach is that, even though the response is consumed after it is caught, you have to poll for it to find out that it has been caught.

In NetBeans IDE, you add support for asynchronous clients to a web service client application by ticking a box in the Edit Web Service Attributes GUI of the web service references. All other aspects of developing the client are the same as for synchronous clients, except for the presence of methods to poll the web service or pass a callback handler and await the result.

The rest of this section details how to create a Swing graphical interface and embed an asynchronous JAX-WS client inside it.

Creating the Swing Form

In this section you design the Swing application. If you prefer not to design the Swing GUI yourself, you can download a predesigned JFrame and go to the section on Creating the Asynchronous Client.

The Swing client gets text you type in, sends it to the service, and returns the number of mistakes and a list of all the wrong words. The client also shows you each wrong word and the suggestions to replace it, one wrong word at a time.

asynch swing client

To create the Swing client:

  1. Create a new Java Application project. Name it AsynchSpellCheckClient . Do NOT create a Main class for the project.

  2. In the Projects view, right-click the AsynchSpellCheckClient project node and select New > JFrame Form…​

  3. Name the form MainForm and place it in the package .

  4. After you create the JFrame, open the project properties. In the Run category, set MainForm as the Main class.

asynch main class
  1. In the Editor, open the Design view of . From the Palette, drag and drop three Scroll Panes into MainForm . Position and size the scroll panes. They will hold the text fields for the text you type in to check, all the wrong words, and the suggestions for one wrong word.

  1. Drag and drop five Text Fields into MainForm . Drop three of them into the three scroll panes. Modify them as follows:

Text Fields

Variable Name

In Scroll Pane?

















  1. Drag and drop a Progress Bar into MainForm . Name the variable pbProgress .

  1. Drag and drop two Buttons into MainForm . Name the first button btCheck and change its text to Check Text or Check Spelling. Name the second button btNextWrongWord , change its text to Next Wrong Word, and disable it.

  1. Drag and drop some Labels into MainForm , to give a title to your application and to describe the text fields.

Arrange the appearance of the JFrame to your liking and save it. Next you add web service client functionality.

Enabling Asynchronous Clients

Add the web service references, as described in Creating the Client. Then edit the web service attributes to enable asynchronous clients.

  1. In the Projects window, right-click the AsynchSpellCheckClient project node and choose New > Other. In the New File wizard choose Web Services > Web Service Client. In the Web Service Client wizard, specify the URL to the web service: Accept all the defaults and click Finish. This is the same procedure from Step 2 onwards described in Creating the Client.

  1. Expand the Web Service References node and right-click the check service. The context menu opens.

asynch edit ws attrib
  1. From the context menu, select Edit Web Service Attributes. The Web Service Attributes dialog opens.

  1. Select the WSDL Customization tab.

  1. Expand the Port Type Operations node. Expand the first CheckTextBodyV2 node and select Enable Asynchronous Client.

enable async client
  1. Click OK. The dialog closes and a warning appears that changing the web service attributes will refresh the client node.

asynch refresh node warning
  1. Click OK. The warning closes and your client node refreshes. If you expand the check node in Web Service References, you see that you now have Polling and Callback versions of the CheckTextBody operation.

asynch ws refs

Asynchronous web service clients for the SpellCheck service are now enabled for your application.

Adding the Asynchronous Client Code

Now that you have asynchronous web service operations, add an asynchronous operation to .

To add asynchronous client code:

  1. In MainForm , change to the Source view and add the following method just before the final closing bracket.

public void callAsyncCallback(String text){

  1. In the Projects window, expand the AsynchSpellCheckClient 's Web Service References node and locate the checkSoap.CheckTextBodyV2 [Asynch Callback] operation.

  1. Drag the CheckTextBodyV2 [Asynch Callback] operation into the empty callAsyncCallback method body. The IDE generates the following try block. Compare this generated code to the code generated for the synchronous client.

try { // Call Web Service Operation(async. callback) service = new; port = service.getCheckSoap();
      // TODO initialize WS operation arguments here
      java.lang.String bodyText = "";<> asyncHandler =
              new<>() {
            public void handleResponse(<> response) {
                  try {
                        // TODO process asynchronous response here
                        System.out.println("Result = "+ response.get());
                  } catch(Exception ex) {
                        // TODO handle exception
      java.util.concurrent.Future<? extends java.lang.Object> result = port.checkTextBodyV2Async(bodyText, asyncHandler);
      while(!result.isDone()) {
            // do something
      } catch (Exception ex) {
      // TODO handle custom exceptions here

In this code, along with the web service invocation, you see that the response from the SpellCheck service is handled through an AsynchHandler object. Meanwhile, a Future object checks to see if a result has been returned and sleeps the thread until the result is complete.

  1. Switch back to the Design view. Double-click the Check Spelling button. The IDE automatically adds an ActionListener to the button and switches you to the Source view, with the cursor in the empty btCheckActionPerformed method.

  1. Add the following code to the btCheckActionPerformed method body. This code gets the text that you type into the tfYourText field, has the progress bar display a "waiting for server" message, disables the btCheck button, and calls the asynchronous callback method.

private void btCheckActionPerformed(java.awt.event.ActionEvent evt) {
    *String text = tfYourText.getText();
    pbProgress.setString("waiting for server");
  1. At the beginning of the MainForm class, instantiate a private ActionListener field named nextWord . This ActionListener is for the Next Wrong Word button that advances one wrong word in the list of wrong words and displays the word and suggestions for correcting it. You create the private field here so you can unregister the ActionListener if it already has been defined. Otherwise, every time you check new text, you would add an additional listener and end up with multiple listeners calling actionPerformed() multiple times. The application would not behave correctly.

public class MainForm extends javax.swing.JFrame {

    private ActionListener nextWord;
  1. Replace the entire callAsyncCallback method with the following code. Note that the outermost try block is removed. It is unnecessary because more specific try blocks are added inside the method. Other changes to the code are explained in code comments.

public void callAsyncCallback(String text) { service = new; port = service.getCheckSoap();
    // initialize WS operation arguments here
    java.lang.String bodyText = text;<> asyncHandler = new<>() {

        public void handleResponse(final<> response) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {

                    try {
                        // Create a DocumentSummary object containing the response.
                        // Note that getDocumentSummary() is called from the Response object
                        // unlike the synchronous client, where it is called directly from
                        // doc = response.get().getDocumentSummary();
//From the retrieved DocumentSummary,
                        //identify and display the number of wrongly spelled words:
final int no_of_mistakes = doc.getMisspelledWordCount();
                        String number_of_mistakes = Integer.toString(no_of_mistakes);
// Check to see if there are any mistakes
                        if (no_of_mistakes > 0) {
//From the retrieved document summary,
                            //identify the array of wrongly spelled words, if any:
final List<> allwrongwords = doc.getMisspelledWord();
//Get the first wrong word
                            String firstwrongword = allwrongwords.get(0).getWord();
//Build a string of all wrong words separated by commas, then display this in tfWrongWords
StringBuilder wrongwordsbuilder = new StringBuilder(firstwrongword);

                            for (int i = 1; i < allwrongwords.size(); i++) {
                                String onewrongword = allwrongwords.get(i).getWord();
                                wrongwordsbuilder.append(", ");
                            String wrongwords = wrongwordsbuilder.toString();
//Display the first wrong word
//See how many suggestions there are for the wrong word
                            int onewordsuggestioncount = allwrongwords.get(0).getSuggestionCount();
//Check to see if there are any suggestions.
                            if (onewordsuggestioncount > 0) {
//Make a list of all suggestions for correcting the first wrong word, and build them into a String.
                                //Display the string of concactenated suggestions in the tfSuggestions1 text field
List<String> allsuggestions = (( allwrongwords.get(0)).getSuggestions();

                                String firstsuggestion = allsuggestions.get(0);
                                StringBuilder suggestionbuilder = new StringBuilder(firstsuggestion);
                                for (int i = 1; i < onewordsuggestioncount; i++) {
                                    String onesuggestion = allsuggestions.get(i);
                                    suggestionbuilder.append(", ");
                                String onewordsuggestions = suggestionbuilder.toString();

                            } else {
                                // No suggestions for this mistake
                                tfSuggestions1.setText("No suggestions");
// See if the ActionListener for getting the next wrong word and suggestions
                            // has already been defined. Unregister it if it has, so only one action listener
                            // will be registered at one time.
if (nextWord != null) {
// Define the ActionListener (already instantiated as a private field)
                            nextWord = new ActionListener() {
//Initialize a variable to track the index of the allwrongwords list

                                int wordnumber = 1;

                                public void actionPerformed(ActionEvent e) {
                                    if (wordnumber < no_of_mistakes) {
// get wrong word in index position wordnumber in allwrongwords
                                        String onewrongword = allwrongwords.get(wordnumber).getWord();
//next part is same as code for first wrong word
                                        int onewordsuggestioncount = allwrongwords.get(wordnumber).getSuggestionCount();
                                        if (onewordsuggestioncount > 0) {
                                            List<String> allsuggestions = allwrongwords.get(wordnumber).getSuggestions();
                                            String firstsuggestion = allsuggestions.get(0);
                                            StringBuilder suggestionbuilder = new StringBuilder(firstsuggestion);
                                            for (int j = 1; j < onewordsuggestioncount; j++) {
                                                String onesuggestion = allsuggestions.get(j);
                                                suggestionbuilder.append(", ");
                                            String onewordsuggestions = suggestionbuilder.toString();
                                        } else {
                                            tfSuggestions1.setText("No suggestions");
// increase i by 1
} else {
                                        // No more wrong words! Disable next word button
                                        // Enable Check button
// Register the ActionListener
} else {
                            // The text has no mistakes
                            // Enable Check button
                            tfWrongWords.setText("No wrong words");
                            tfSuggestions1.setText("No suggestions");

                    } catch (Exception ex) {
// Clear the progress bar


    java.util.concurrent.Future result = port.checkTextBodyV2Async(bodyText, asyncHandler);
    while (!result.isDone()) {
        try {
//Display a message that the application is waiting for a response from the server
        } catch (InterruptedException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
  1. Press Ctrl-Shift-I (⌘-Shift-I on Mac) and fix imports. This adds the following import statements:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;

You can now build and run the application! Unfortunately, you are unlikely to see what happens during a long delay in getting a response from the server, because the service is quite fast.

Applying What You Have Learned

Now that you have completed your first web service client in the IDE, it is time to stretch your skills and extend the application to be all that it was destined to be. Below are two suggested tasks to get you started.

  • Add error handling code to the servlet.

  • Rewrite the client so that the user can interact with the data returned from the web service.

See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:

To send comments and suggestions, receive support, and stay informed about the latest developments on the NetBeans IDE Java EE development features, join the mailing list.