Saturday, March 11, 2006

The easiest way to create a webservice in EJB3

As you certainly already know, webservoces rules the world. You can call them from almost anywehere means any platform, any technology. To create a webservice in the world of EJB2.1 and related technologies used to be a tough task. The upcoming EJB3 is changing a lot in this area. From the developer's point of view, the main change is that to create a webservice he/she doesn't need to be a guru. For demostration purpose I've created a tiny Webservice. Actually it doesn't do anything useful just calls to underlaying EJB.
The very basic principle of creation of webservice is to develop class that is an EJB (stateless or stateful) and mark it as a webservice. It means annotate class as @Stateless and @WebService. If you do that, you've got a webservice but unfortunetaly without any accessible method. To publish a method as a web method simply annotate a method with @WebMethod annotation. And here is the example of WebService:
package org.defectus.ejb3.ws;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;

@Stateless
@WebService(serviceName = "ResultService")
public class Service {

@WebMethod(operationName="TestResult")
public long testResult (long id {
return id;
}

@WebMethod(operationName="StringResult")
public String stringResult (String id) {
if (id == null)
return "null";
return id;
}
}
The next step is to deploy such webservice. It should be an easy thing but for me it's not like that. I don't know why but to successfuly deploy webservice I have to call WSGEN manually. Manually in my particular case means to call an ant's task. For example like this:
<target name="generate-wsdl" depends="compile-ejb">
<mkdir dir="${build.dir}/generated/wsdl" />
<mkdir dir="${build.dir}/service" />
<exec executable="${appserver.dir}/bin/wsgen" failonerror="true">
<arg line="-extension -cp ${build.dir} -d ${build.dir} -r ${build.dir}/generated/wsdl -wsdl org.defectus.ejb3.papp.ws.ResultService" />
</exec>
</target>

After you deploy the webservice don't forget to use a nice feature of glassfish - webservice tester. Just locate the webservice in administration console adn click the Test button.
And that's all for now. I'll try to find another feature to explain latter ...

2 comments:

Anonymous said...

The next step is to deploy such webservice. It should be an easy thing but for me it's not like that. I don't know why but to successfuly deploy webservice I have to call WSGEN manually. Manually in my particular case means to call an ant's task.

Open source project GlassFish supports auto-deployment that makes this very easy. See the following article for more details.

-- Nazrul

Anonymous said...

Project GlassFish supports auto-deployment that makes it easy. See
http://developers.sun.com/prodtech/appserver/reference/techart/ws_mgmt.html

--Nazrul