站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Consuming Web Services in NetBeans IDE 4.1(2)

Consuming Web Services in NetBeans IDE 4.1(2)

摘要: This article will show you how to use NetBeans IDE 4.1 to consume a simple web service quickly and easily. It will demonstrate the web service facilities available in NetBeans IDE 4.1, but will not delve into too much detail.

This article assumes you understand the basic process flow of creating a client for consuming web services in NetBeans IDE 4.1. The basic process flow is described in Part 1. In Part 1, a very simple web service is consumed -- the invoked operation requires no arguments to be passed. In Part 1 you do not need to analyze the web service, because it is so simple. In Part 2 you use the web service facilities provided by NetBeans IDE 4.1 to analyze the web service, before building the client. You need to do this because the web service is fairly complex. Once you have analyzed the web service, you use NetBeans IDE 4.1 to create a client that consumes it.

A spell checker web service is consumed by the client that you create in this tutorial. In this tutorial you 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.

This tutorial covers the following topics:

Note: 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. As pointed out in Part 1, 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.

After you have installed and set everything up, the tutorial can be completed in 60 minutes.

Getting Started

Installing the Software

Before you begin, you need to have the following software installed on your computer:

  • NetBeans IDE 4.1 (download).
  • Sun Java System (SJS) Application Server Platform Edition 8 2005Q1 (download)
  • Java Standard Development Kit (JDKTM) version 1.4.2 (download) or 5.0 (download)

Registering the Sun Java System Application Server

Before you can create, compile, and deploy web services, you have to register a local instance of the SJS Application Server. If you installed the NetBeans IDE 4.1/SJS Application Server bundle, the local application server is registered automatically.

  1. Choose Tools > Server Manager from the main window.
  2. Click Add Server. Select Sun Java Systems Application Server 8.1 and give a name to the instance. Then click Next.
  3. Specify the server information, the location of the local instance of the application server, and the domain to which you want to deploy.

If you are behind a firewall, you need to set a proxy host and port number on the SJS Application Server. See the first part of Troubleshooting for help.

Getting to Know the Sample

  1. Unzip the sample attached to the top of this page.

  2. In the IDE, choose File > Open Project and browse to the folder that contains the unzipped file. Open the project. It should look as follows:

    Projects window

  3. Right-click the project node and choose Run Project. The user interface, consisting of a JSP page, should be displayed. Enter some text:

    Entry page

    Make sure that you provide a few incorrectly spelled words!

    If the application does not deploy or if the JSP page is not displayed, see the Troubleshooting section at the end of this tutorial.

  4. Click Spell Check. The entered text is sent by a servlet to the spell checker web service. The spell checker web service then processes the text. It works out how many words are wrong, identifies the wrong words, and generates a list of suggested alternatives. Once it has completed its work, it returns the information to the servlet, which organizes it and produces a report:

    Entry page

Now that you are familiar with the sample, you are ready to find out how to build it from scratch.


Consuming the Spell Checker Web Service

To consume a web service, you need to create a web service client. For the creation of web service clients, NetBeans IDE 4.1 provides a client creation facility -- 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 and a built-in client for testing and analyzing web services. These facilities are part of the standard NetBeans IDE installation, they're available straight out of the box and no plug-ins are needed.

Creating the Client

  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, choose Web. Under Projects, choose Web Application. Click Next. Name the project SpellCheckService and make sure that you specify the Sun Java System Application Server as your target server. Click Finish.

  2. In the Projects window, right-click the SpellCheckService project node and choose New > File/Folder. In the New File wizard choose Web Service > Web Service Client. In the Web Service Client wizard, specify the URL to the web service:

    http://ws.cdyne.com/SpellChecker/check.asmx

    Click Retrieve WSDL to download it. If you are behind a firewall, you might need a proxy -- otherwise the WSDL file cannot be downloaded. If so, click Proxy Settings in the Web Service Client wizard and set your proxy host and port number.

  3. Enter org.netbeans.end2end.check.client as the package name. The package name specifies the package to which the client files will be generated.

  4. Click Finish.

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

    Projects window

    The Projects window shows that a web service called 'Check' has made the operations 'checkTextBody' and 'suggestWord' available to your application. The 'checkTextBody' operation checks a string for spelling errors and returns data to be processed by the client. You will use this operation throughout this tutorial. The 'suggestWord' operation, for suggesting words to the web service's dictionary, will not be used.

    In the Files window, within the build node, you should see the following:

    Files window

    The Files window shows five files:

    • Check.java. Interface that extends javax.xml.rpc.Service.
    • CheckSoap.java. Interface that extends java.rmi.Remote.
    • CheckSoap_Impl.java. Implementation class for CheckSoap.java. Two operations are implemented, checkTextBody(java.lang.String bodyText, java.lang.String licenseKey) and suggestWord(java.lang.String word).
    • DocumentSummary.java. Complex DocumentSummary object for accessing the returned text, the Words object containing the misspelled words, the number of misspelled words, and the version of the web service.
    • Words.java. Complex Words object for accessing an array of data for each misspelled word. The data consists of the misspelled word itself, an integer containing the number of suggested alternatives, and an array containing the suggested alternatives.

Testing the Web Service

  1. In the Projects window, within the Web Service References node, double-click the 'checkTextBody' operation. The Test Web Service Operation dialog box appears.

  2. Type values for the arguments required by the operation:

    • bodyText. The text that you want to have checked. Remember to include a few incorrectly spelled words.
    • licenseKey. The license key required by the web service. Type 0.

  3. Click Submit. When you do this, the web service is contacted and the operation is invoked. Wait for the text to be checked and returned (it should not take long). You should then see something similar to the following:

    Test Web Service Client wizard

If you see something similar to the results displayed in the above illustration, your test has succeeded. The web service is up and running and has processed your text. The built-in client has contacted the web service, passed it your values, and retrieved a result. If a result is not returned and you are behind a firewall, see the second part of Troubleshooting for help.

Analyzing the Web Service

When the IDE generates the web service client's files, using the information you specify in the Web Service Client wizard, it generates a Java object for each complex data type defined in the WSDL file. The spell checker WSDL file contains two complex data types, DocumentSummary and Words:

<s:complexType name="DocumentSummary">
 <s:sequence>
   <s:element minOccurs="0" maxOccurs="unbounded" name="MisspelledWord" type="s0:Words" />
   <s:element minOccurs="0" maxOccurs="1" name="ver" type="s:string" />
   <s:element minOccurs="0" maxOccurs="1" name="body" type="s:string" />
   <s:element minOccurs="1" maxOccurs="1" name="MisspelledWordCount" type="s:int" />
 </s:sequence>
</s:complexType>

<s:complexType name="Words">
 <s:sequence>
   <s:element minOccurs="0" maxOccurs="unbounded" name="Suggestions" type="s:string" />
   <s:element minOccurs="0" maxOccurs="1" name="word" type="s:string" />
   <s:element minOccurs="1" maxOccurs="1" name="SuggestionCount" type="s:int" />
 </s:sequence>
</s:complexType>

In order to successfuly implement the client, you need to work with these complex data types and the data each provides. The IDE provides several tools to enable you to graphically examine each complex data type, represented by its related Java object, and unpack its data. Below you are shown how to do this, using the WSDL for CDYNE's spell check web service as an example.

Examining the DocumentSummary Object

  1. Open the Test Web Service Operation dialog box for the 'checkTextBody' operation, as described in the previous section. Fill in some text, type 0 for the licenseKey argument, and click Submit.

    The lower part of the Test Web Service Operation dialog box displays the following:

    Test Web Service Client wizard

    This is the outermost layer of the web service. Before we can do anything else, we need to deal with this layer. Note that the highest node is called DocumentSummary.

  2. In the Files window (Ctrl-2), expand the build folder until you get here:

    Now double-click the DocumentSummary.java node so that it opens in the Source Editor (and look at the nodes above as well). Doing this shows you what methods are made available by DocumentSummary.java. Once you've opened it in the Source Editor (accompanied by viewing its expanded nodes in the Files window), you can see that the corrected text returned by the SpellChecker service should be assigned to the DocumentSummary object. Once this is done, you can use its methods to interact with the corrected text. In the next section, you use the DocumentSummary object as follows (the bold code below highlights the methods provided by the DocumentSummary object):

        DocumentSummary doc = getCheckSoap().checkTextBody(text,"0");
        String allcontent = doc.getBody();
        int no_of_mistakes = doc.getMisspelledWordCount();
        Words[] allwrongwords = doc.getMisspelledWord();

    While the Words object needs to be processed before you can do anything with it, the allcontent string and the no_of_mistakes integer can be used right away. For example, at the top of the report you might want to display the text that you sent to the web service. This text is provided by allcontent (bold in the code below):

        out.println("<b>Your text:</b> \"" + allcontent + "\"<p>");

    Displayed in the browser, the result of the above line of code is as follows:

    Display in browser

    There's another method, called getVer, but you do not need to use that in this tutorial. On the other hand, if you were going to make your client implementation generally available, and really use it in a business setting, it might be useful to run through a condition to check if the web service's version is the one that you expect it to be -- and produce some kind of error or message when the versions differ -- because subsequent versions of the web service might clash with your client implementation.

Examining the Words Object

  1. In the Test Web Service Operation dialog box, expand the DocumentSummary node. Now expand the Words[] node and one of its subnodes. The lower part of the Test Web Service Operation dialog box now displays the following:

    Test Web Service Client wizard

    This is the Words object. It contains an array called Words for each misspelled word. In the illustration above, you can see the Words array for the misspelled word "spelll".

  2. In the Files window (Ctrl-2), expand the build folder until you get here:

    Now double-click the Words.java node so that it opens in the Source Editor (and look at the nodes above as well). Doing this shows you what methods are made available by Words.java. Once you've opened it in the Source Editor (accompanied by viewing its expanded nodes in the Files window), you can see that each misspelled word should be assigned to the Words array, which you access using the Words object. Once this is done, you can use the Words object's methods to interact with each misspelled word individually. In the next section, you use the Words object as follows (the bold code below highlights the methods provided by the Words object):

      for (int i = 0; i < allwrongwords.length; i++) {
    
        String onewrongword = allwrongwords[i].getWord();
        int onewordsuggestioncount = allwrongwords[i].getSuggestionCount();
        String[] allsuggestions = allwrongwords[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.length; k++) {
          String onesuggestion = allsuggestions[k];
          out.println(onesuggestion);
        }
    
      }

    Displayed in the browser, the result of the above lines of code is as follows:

    Display in browser

    To round things off, you can provide a summary at the end:

      out.println("<font color='red'><b>Summary:</b> " + no_of_mistakes + " mistakes (");
      for (int i = 0; i < allwrongwords.length; i++) {
          String onewrongword = allwrongwords[i].getWord();
          out.println(onewrongword);
      }
      out.println(").");
      out.println("</font>");

    Displayed in the browser, the result of the above lines of code is as follows:

    Display in browser

    Of course, many variations are possible. Once you can access the methods you need, you can loop through the returned data quite easily and do whatever you like with it.

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 should expect to 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 JSP 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 JSP Page

  1. In the Projects window, expand the Web Pages node and double-click index.jsp so that it opens in the Source Editor.

  2. Copy the following code and paste it over the <body> tags in index.jsp:
    <body>
      <form name="Test" method="post" action="SpellCheckServlet">
         <p><font color='red'>Enter the text you want to check:</font></p>
         <p>
         <p><textarea rows="7" name="TextArea1" cols="40" ID="Textarea1"></textarea></p>
         <p>
         <input type="submit" value="Spell Check" name="spellcheckbutton">
      </form>
    </body>

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

Creating and Coding SpellCheckServlet

  1. Right-click the project node in the Projects window, choose New > File/Folder and then choose Web > Servlet. Click Next. Name the servlet SpellCheckServlet and type org.netbeans.end2end.check.client in the Package drop-down. Click Next. Note that the URL mapping for this servlet is /SpellCheckServlet and click Finish. The servlet opens in the Source Editor.

  2. Put your cursor inside the Source Editor, inside the processRequest method, right-click, and choose Web Service Client Resources > Call Web Service Operation. Click the checkTextBody operation in the "Select Operation to Invoke" dialog box and then click OK.

    Bits of code have now been added to the servlet. Scroll to the bottom, and you see code that connects the client to the web service (much of the code is underlined in red -- ignore that, it's a bug that has no effect on the building and running of the application).

    At the top of the processRequest method you see a snippet of code that invokes the web service. This method is all you need to work with to invoke the operation on the web service.

  3. Replace the entire processRequest method with the code that follows. The in-line comments throughout the code below explain the purpose of each line.
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
    
    //Get content from JSP:
            String TextArea1 = request.getParameter("TextArea1");
    //Invoke the operation on the web service that does the spell check.
    //As arguments, send the content and the key:
            DocumentSummary doc = getCheckSoap().checkTextBody(TextArea1,"0");
    //From the retrieved document summary,
    //identify all the content, correct and incorrect:
            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:
            Words[] allwrongwords = doc.getMisspelledWord();
    
            out.println("<html>");
    out.println("<head>");
            //Display the report's name as a title in the browser's titlebar:
            out.println("<title>Spell Checker Report</title>");
            out.println("</head>");
            out.println("<body>");
    //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
    //suggestion:
            for (int i = 0; i < allwrongwords.length; i++) {
                String onewrongword = allwrongwords[i].getWord();
                int onewordsuggestioncount = allwrongwords[i].getSuggestionCount();
                String[] allsuggestions = allwrongwords[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.length; k++) {
                    String onesuggestion = allsuggestions[k];
                    out.println(onesuggestion);
                }
            }
    //Display a line after each array of wrong words:
            out.println("<hr>");
    //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.length; i++) {
                String onewrongword = allwrongwords[i].getWord();
                out.println(onewrongword);
            }
            out.println(").");
            out.println("</font>");
            out.println("</body>");
            out.println("</html>");
            out.close();
        }
  4. Note that error handling has not been dealt with in the code above. See Applying What You Have Learned for details.

  5. Save the servlet. Remember that you can ignore the red underlinings in the web service methods generated by the IDE -- it's a known bug that has no effect on the building and running of the application.

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 finetune 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 Project.

    After a while, the application should deploy and display the JSP page that you coded in the previous section. Enter some text, making sure that some of it is incorrectly spelled:

    Projects window

  2. Use the application as described in Getting to Know the Sample. For troubleshooting, see Troubleshooting.

Applying What You Have Learned

Troubleshooting

Since the IDE provides most of the code you need for communicating with the web service, the only problems you should encounter are errors in your own code. In addition, though, you might encounter a few problems if you are behind a firewall. The troubleshooting tips that follow attempt to resolve these problems

Next Steps

For more information about using NetBeans IDE 4.1, see the following resources:

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE J2EE development features, join the mailing list .


↑返回目录
前一篇: Consuming Web Services in NetBeans IDE 4.1(1)
后一篇: Creating Shortcuts to Your Custom ANT Tasks