Netbeans: a simple Webservice with just one line of code

Web Services (WS)  in Java can be realized using several technologies, in this short tutorial I will demonstrate how to implement a very basic Web Service in an ejb-module with just a single line of code.

The Web Service we are going to Implement will perfom one simply operation, it will take an input argument of type int and return it’s square. Just like the method:

public int square(int a) {

return a*a

}

would do.

Requirements:

  • Netbeans >= 6.5
  • Glassfish Applicationserver
  • about 10minutes time

First, fire up Netbeans, start up your application server and create a new ejb-module project enter a project name and finish the wizard.

[SubWindow] Application sub-Dialog New Project

Then right-click the project’s node and choose new – Web Service.

[Menu] Popup menus

Type in a name and a package and again, finish the wizard.

[SubWindow] Application sub-Dialog New Web Service

Netbeans will generate some code and show you this.

[Mode] editor (myWebservice.java)

Now a Web Service has already been generated it just doesn’t serve any operations yet. To add an operation, right click your Web Service and choose add operation.

[Menu] Popup menus (clipped)

The Add Operation Dialog will show up.

You can imagine a Webservice Operation like a usual method and since we are going to implement a square operation the method would look like this:

public int square(int a) {

return a*a

}

So all you have to do now, is to set the operation’s Return Type, as well as the number and type of Arguments, it takes.

[SubWindow] Application sub-Dialog Add Operation

Since we are working with numbers here, click Browse and select Integer for the Return type.

[SubWindow] Application sub-Dialog Find Type

When you’re done, click OK and the IDE will take you to your Operation’s skeleton.

[TopComponent] myWebservice.java

All that’s left to do here is to implement the Operation’s actual logic, and for our square operation we simply return the square of it’s input and here it comes, the one line of code we’ll actually write.

return input*input

[Mode] editor (myWebservice.java)

That’s it!  Now build and deploy the WS, afterwards you can quickly test it by right-clicking the project-node and choosing “Test Web Servive”. Your Browser will start up and show the Test Interface your Application Server provides.

[Menu] Popup menus

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: