Brewing Java Web services with NetBeans 4.1 - Java - Techguide

Brewing Java Web services with NetBeans 4.1

 

Summary

Ever wondered how to write a Web service in Java? We show you how using NetBeans, the open source Java development environment for Windows, Linux and OS X.

Events

IBM Technology Conference & Expo 2012
May 22, 2012

One World Hotel, First Avenue, Bandar Utama City Centre, 47800 Petaling Jaya, Selangor

Echelon 2012
June 11 and 12, 2012

University Cultural Centre, National University of Singapore

Startup Asia Jakarta 2012
June 7 and 8, 2012

12th Floor, Annex Building, Wisma Nusantara Complex, Jl. M.H. Thamrin No. 59 Jakarta 10350, Indonesia

MMA Forum Singapore
April 23-25, 2012

Grand Hyatt Singapore

Ever wondered how to write a Web service in Java? We show you how using NetBeans, the open source Java development environment for Windows, Linux and OS X.

In this tutorial we take a fresh look at building Web services using the latest release of NetBeans, an open source Java GUI for Windows, Linux and OS X. This tutorial is designed for Web application developers of any level, whether you have Java experience or not. It should take you less than an hour from start to finish, which is a testament to the maturity of Java development tools such as NetBeans. So let's dive in.

Installation and configuration
To get up and running with Java Web services, you need the latest version of the Java 2 SDK and the Java Web Services Developer Pack. To complete this tutorial you will also need NetBeans 4.1 and the Sun Application Server. If possible, it is best to install these in the following order:

  1. Java 2 Standard Development Kit 1.4.2;
  2. Java Web Services Developer Pack 1.5;
  3. Sun Java Systems Application Server Platform Edition 8 2005Q1;
  4. NetBeans 4.1 RC2 or later.

Once you have all the above software installed, you will need to configure NetBeans to use the Sun Application Server instead of the bundled TomCat server by default. To do this, go to Tools -> Server Manager and click Add Server. Here you need to locate the server's installation directory and supply the login you created during the setup process.

Creating the Web service
From the NetBeans File menu select New Project and choose Web Application from the dialog box before clicking Next. In the New Web Application window, specify a name and location for the project and click Finish. NetBeans will now create an empty Web application with a default JSP page that opens in the editor pane. Right click the project node in the Projects pane and select New -> Web Service from the menu. Here, specify a name and package namespace for the Web service.

Figure 1: Adding a handler

The .java file will now open in the editor with an empty Web service template class. To add an operation, right click within the editor and choose Web service -> Add operation from the menu. In the dialog that appears, specify a name for the operation and create any required parameters. For our simple maths example, we created an operation called "squared" with accepts and returns a floating point number. The code for the Web service will now look something like this:

package demo.maths.ws;
public class SimpleMathsWSImpl implements
SimpleMathsWSSEI {
  public float squared(float num) {
    // TODO implement operation
    return 0;
  }
}

The next step is to implement the function for the operation. Our squared routine simply returns the input parameter value multiplied by itself. Hence the final code for the operation looks like this:

public float squared(float num) {
  return num * num;
}

Figure 2: Starting a Web service

We now need to make the Web service the default handler for the application, and this is done from the project properties window. Right click the project in the Projects pane and select properties. Next, select the run node and enter the name of the Web service in the Relative URL field. Our Web service is called SimpleMathsWS, so we used /SimpleMathsWS as the default URL for the project. It is now possible to build and deploy the project so the Web service can be registered and consumed. Simply right click the project and choose Run from the menu. The default browser will open and show the following error message.

Invalid wsdl request
http://localhost:8080/SimpleMathsWS/SimpleMathsWS for web service SimpleMathsWS

This means our Web service is working, but a valid request was not made. The Web service is now ready to be consumed by a Web service client, but first, let's add a SOAP message handler that logs the activity of the Web service.

Figure 3: Browser output

Adding a SOAP message handler
Right click the project node and select New -> File/Folder. From the Web Services category, select Message Handler and click Next. Specify a name and package for the handler and click Finish.

To apply the new message handler to the Web service, browse to the Web service from the Web Services node in the Projects pane and right click it. From the menu select Configure Handlers and click Add in the dialog box. Browse the source packages until you find the message handler just created. Select it and click OK. Click OK again to close the SOAP message handler manager window.

Figure 4: Select an operation.

Now run the project again and switch to the Runtime pane in the IDE. Right click the Sun Java System Application Server node and choose View Server Log. At the bottom of the Output pane you will find an entry produced by the SOAP handler that looks something like the following.

Log message: Thu May 05 20:04:45 EST 2005--squared float_1:1.0 |#]

This is good news. It means not only is the Web service running but the SOAP message handler is also operational. Now it's time to register the Web service so that it can be consumed by clients. To do this, return to the Projects pane, right click the Web service and select Add to registry. Before clicking OK, however, copy the URL in the dialog box to the clipboard. We'll need this for the Web service client application.

Creating a Web service client
Keeping the current project open, create a new Web application project for the Web service client. Right click the project in the Projects pane and select New -> Web Service Client. In the configuration window that appears, paste the URL that was copied from the Web service registration dialog box into the WSDL URL field and click the Retrieve WSDL button. A wsdl file will be created and its file name displayed in the Local Filename field. Enter the package name for the client and click Finish.

Now if you browse to the Web Service References node in the Projects pane you will find the Web service and its operation are available in the object tree. Right clicking the operation allows you to run a test on the operation using a supplied value. After establishing that the test works, it is now possible to create a servlet to access the Web service.

Consuming the Web service from a servlet
Right click the project once again, this time selecting New -> Servlet. Provide a name and package for the file, click Next, and enter a URL mapping for the servlet. You can also specify default parameters here that can be passed programmatically to the Web service if desired.

Right click inside the processRequest method of the new servlet and select Web Service Client Resources -> Call Web Service Operation. This will display a list of registered Web service operations from which to choose. Select the desired method and click OK. You will now need to supply the parameter to pass to the Web service as well as configuring the method to output to the response object. By the end, you should have something like this in your servlet code.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String num = request.getParameter("num");
    if (num == null || num.length() < 1){
      num = "1";
    }
    float f = Float.valueOf(num).floatValue();
    try {
      out.println(getSimpleMathsWSSEIPort().squared(f));
    } catch(java.rmi.RemoteException ex) {
      out.println("Exception thrown: " + ex);
    }
    out.close();
  }

This code looks for a URL parameter called num and passes it to the Web service once the value is converted to a floating point number. For brevity, validation code has been omitted with the exception of a simple check for a null or empty value. The Web service client is now complete. Simply set the default URL for the project to be the same as the servlet mapping you provided earlier, and then run the application. A URL parameter can now be supplied to the servlet via the browser which will return the value produced by the Web service.

Figure 5: Register your Web service.

Deploying the application
The application is now ready to go. For convenience, you can create an Enterprise application in NetBeans which bundles both the Web service and client projects into a single package. You can disable the EJB and Web application modules during creation and then add the existing projects by right clicking the J2EE Modules node in the Projects pane. With this completed, you need to select the Web service client project as the default module and enter the relative URL belonging to the servlet. The entire application can now be deployed after undeploying the sub-projects from the server. This is done from the Runtime pane. First, navigate to the Web Applications node under the Sun Java System Application Server node. Then right click each project and select undeploy. You can now deploy and run the Enterprise project, which will open the default browser to the location of the Web service client servlet.

Talkback

Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment

ZDNet Asia Live

Pakistan lifts block on Twitter - ZDNet Asia: Pakistan lifts block on TwitterZDNet Asia59 Jakarta 10350, Indones... http://t.co/61n85ajh

Pakistan lifts block on Twitter http://t.co/WHqoJOqm http://t.co/erFX4aVv #arcavir

http://t.co/VNaZtseV Pakistan lifts block on Twitter: Country restores access after briefly ... http://t.co/5gqegFWK http://t.co/wiqY9ktt

Pakistan lifts block on Twitter. http://t.co/y0arswpE

Mac users' indifference toward security 'worrying'. http://t.co/i7gZ8WVn

Mac users' indifference toward security 'worrying' - ZDNet Asia: Mac users' indifference toward security 'worryi... http://t.co/CD9pvW08

RT @zdnetasia: Mac users' indifference toward security 'worrying'. http://t.co/i7gZ8WVn

Mac users' indifference toward security 'worrying' - ZDNet Asia: USA TODAYMac users' indifference toward securit... http://t.co/4EUVidiO

Mac consumers indifferent about security, security vendors warn such mindset is "worrying" http://t.co/ZGIxdg67 #In

Mac users take note! RT @zdnetasia: Mac users' indifference toward security 'worrying'. http://t.co/YrLB9btb #mac #apple

RT @zdnetasia: Mac users' indifference toward security 'worrying'. http://t.co/i7gZ8WVn

Mac users' indifference toward security 'worrying': However, Mac users ZDNet Asia spoke to expressed indifferenc... http://t.co/15DulmWS

RT @jolintan: Mac users take note! RT @zdnetasia: Mac users' indifference toward security 'worrying'. http://t.co/2RQkfCKt #mac #apple

APAC tech merger and acquisition in Q1 down but value up: http://t.co/V7UkMABl

Mac users' indifference toward security 'worrying' - ZDNet Asia: Mac users' indifference toward security 'worryi... http://t.co/PINqvJxT

I reckon your view: "CRM is strategy, not software", if a company replicating the approach uses in ERP implementation into CRM, what they...

2 hours ago by wykoong on Gartner: Mobile CRM gives better ROI than social

This video will teach you about the Excel fill handle but also provide you with a workook to download... http://www.youtube.com/watch?v=...

19 hours ago by TradeBrother on A quick fill handle trick for Microsoft Excel

waiting...

2 days ago by eapete on What should count in a company's market value?

Boy, you've opened a can of worms now.

Wait for the rants & raves.

2 days ago by eapete on What should count in a company's market value?

I was puzzling before this whether to replicate the success formula we executed for a financial institute, and come out with a standard s...

3 days ago by wykoong on Drop the egos, copy ideas, then innovate