Sunday, January 14, 2007

how to write a web service in java

Steps to write a Web Service :

1. Write the business implementation class under a package.

HelloWorld.java

package wsdemo;

public final class HelloWorld

{

public String sayHello(String s)

{

System.out.println("HelloWorld from your WebService");

System.out.println("This message brought to you by " + s);

return "Hello " + s;

}

}

2. compile the file

eg : javac –classpath . HelloWorld.java –d .

3. save the following build.xml file under the current working folder build.xml

targetNamespace="http://localhost/webservices/hello"

serviceName="HelloWorld"

serviceURI="/HelloWorld"

generateTypes="True"

expandMethods="True">

4. set the classpath as per the following command

set classpath=%classpath%;c:\bea\jdk141_03\lib\tools.jar;c:\bea\weblogic81\server\lib\weblogic.jar;c:\bea\weblogic81\server\lib\weblogic_sp.jar;c:\bea\weblogic81\server\lib\webservicesclient.jar;c:\bea\weblogic81\server\lib\webservices.jar;

5. Run the ant tool to generate an HelloWorld.ear file

eg: java -classpath .;%classpath% org.apache.tools.ant.Main

6. Deploy the ear file with the application server through console application

7. Write the client application

Client.java

import wsdemo.*;

public class Client

{

public static void main(String[] args) throws Exception

{

String service_url =

"http://localhost:7001/webservices/HelloWorld?WSDL";

System.out.println(service_url);

HelloWorld_Impl h = new HelloWorld_Impl(service_url);

HelloWorldPort port =

h.getHelloWorldPort();

String result = port.sayHello(args[0]);

System.out.println(result);

}

}

8. Save the following build.xml file under the same folder where the client app is existing

packageName="wsdemo"

clientJar="myclient.jar">

9. Run the following ant command to generate myclient.jar file

eg: java -classpath .;%classpath% org.apache.tools.ant.Main

10. Compile the client application by keeping the myclient.jar file in the classpath

javac -classpath .;myclient.jar;%classpath% Client.java

11. Run the client application to test the web service

java -classpath .;myclient.jar;%classpath% Client John

0 Comments:

Post a Comment

<< Home