Monday, October 26, 2009

Web Services using JAX-RS

JAX-RS stands for Java API for RESTful Web Services. RESTful API came in JSR-311.
I am using Apache CFX to develop web service for RESTful. You can download the libraries from http://cxf.apache.org/. More documentation is available at http://cxf.apache.org/docs/jax-rs.html

Use the following steps to create a web service.

1. Create a web project, say Calculator

2. Create Addition.java

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/addition/")
@Produces("text/html")
@Consumes("text/html")
public class Addition {

  @GET
  @Path("/add/{a}/{b}")
  public int add(@PathParam("a") int a, @PathParam("b") int b) {
    return a + b;
  }
}

3. Add the following in web.xml under WEB-INF.
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>WEB-INF/beans.xml</param-value>
</context-param>

<listener>
  <listener-class>
    org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>

<servlet>
  <servlet-name>CXFServlet</servlet-name>
  <servlet-class>
    org.apache.cxf.transport.servlet.CXFServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>CXFServlet</servlet-name>
  <url-pattern>/service/*</url-pattern>
</servlet-mapping>

4. Create beans.xml, and put it into WEB-INF. The content of beans.xml is

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxrs
    http://cxf.apache.org/schemas/jaxrs.xsd">

  <!-- do not use import statements if CXFServlet init parameters link     to this beans.xml -->

  <import resource="classpath:META-INF/cxf/cxf.xml" />
  <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
  <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

  <jaxrs:server id="services" address="/service">
    <jaxrs:serviceBeans>
      <ref bean="additionBean" />
    </jaxrs:serviceBeans>
    <jaxrs:extensionMappings>
      <entry key="xml" value="application/xml" />
    </jaxrs:extensionMappings>
  </jaxrs:server>

  <bean id="additionBean" class="calculator.Addition" />
</beans>

5. Add libraries to the web project.

6. You can access the web service using http://localhost:8080/Calculator/service/service/addition/add/23/36.

Here we are passing 23 and 36 to our add method in Addition.java.
The result you will see is 59.

You can see the wadl using http://localhost:8080/Calculator/service/service/addition?_wadl&_type=xml

No comments:

Post a Comment