Java API for XML Web Services is a Java API use to build Web Services and Client.
The following are the requirements for this example to work:
a. Apache Tomcat 6 - this sample code was tested using version 6.
b. Java 1.5 or higher
c. Eclipse - Kepler version was used to code this example.
c. Knowledge of XML, WSDL and SOAP.
Step 1: Create Web Service that will run in Apache Tomcat.
a. Create Dynamic Web Project in Eclipse IDE.
e.g. Create wsexample project.
b. Create Hello interface class.
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface Hello
{
@WebMethod
public String sayHello(String name);
}
c. Create implementation class of Hello interface.
import javax.jws.WebService;
//Service Implementation
@WebService(endpointInterface = "com.mago.ws.example.Hello")
public class HelloImpl implements Hello
{
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
d. Create sun-jaxws.xml under wsexample > WebContent > WEB-INF folder.
<?xml version="1.0" encoding="UTF-8"?>
<endpoints
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="Hello"
implementation="com.mago.ws.example.HelloImpl"
url-pattern="/hello"/>
</endpoints>
e. Update web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>jaxws</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jaxws</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
</web-app>
f. Export wsexample project as WAR file. Right click on the wsexample > Export > wsexample.war. You can save this directly to Apache Tomcat webapps folder.
i.e. wsexample.war
Step 2: Create Web Service Client.
a. Generate client class from WSDL using wsimport:
wsimport -keep -verbose http://localhost:8080/wsexample/hello?wsdl
b. Create client by using generated client classes from wsimport:
import javax.xml.ws.WebServiceRef;
import com.mago.ws.example.client.Hello;
import com.mago.ws.example.client.HelloImplService;
public class HelloClient {
private static HelloImplService service;
public static void main(String[] args)
{
HelloImplService service = new HelloImplService();
Hello port = service.getHelloImplPort();
String sayHello = port.sayHello("Robin");
System.out.println(sayHello);
}//end main
}//end class
c. Run HelloClient.
That's it!
Note: For quick testing you can use SOAPUI.
No comments:
Post a Comment