Wednesday, November 4, 2009

Web Services using JAX-WS

Use following steps to create a web service using JAX-WS.
1. Create a web project, say Calculator.
2. Create a class Addition.java

  package org.me.calculator;

  import javax.jws.WebMethod;
  import javax.jws.WebParam;
  import javax.jws.WebService;

  @WebService()
  public class Addition {
    /**
    * Web service operation
    */
    @WebMethod(operationName = "add")
    public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {
      return a + b;
    }

  }

3. Edit web.xml under WEB-INF, add
  <listener>
    <listener-class>
      com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    </listener-class>
  </listener>
  <servlet>
    <servlet-name>CalculatorWS
    <servlet-class>
      com.sun.xml.ws.transport.http.servlet.WSServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>CalculatorWS
    <url-pattern>/webservice/*</url-pattern>
  </servlet-mapping>

4. Add sun-jaxws.xml in WEB-INF. and add the following contents:
<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
  <endpoint implementation="org.me.calculator.Addition" name="Addition" url-pattern="/webservice/Addition"/>
</endpoints>

5. Add required JAR into the project.

6. Deploy the project and run using http://localhost:8080/Calculator/webservice/Addition. You can see the WSDL using http://localhost:8080/Calculator/webservice/Addition?wsdl

No comments:

Post a Comment