当前页面: 开发资料首页 → Netbeans 专题 → 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.
Before you begin, you need to have the following software installed on your computer:
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.
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.
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.
Now that you are familiar with the sample, you are ready to find out how to build it from scratch.
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.
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.
In the Projects window, within the Web Service References node, you should see the following:
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:
The Files window shows five files:
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.
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.
The lower part of the Test Web Service Operation dialog box displays the following:
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.
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:
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.
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".
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:
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:
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.
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.
<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.
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.
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(); }
Note that error handling has not been dealt with in the code above. See Applying What You Have Learned for details.
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).
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:
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
To fix this problem, do the following:
Make sure that the values you set for these properties are appropriate to your environment.
The dialog box should now look similar to the following:
To fix this problem, do the following:
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 .