Bright Java Tutorial

is brought to you by DoITBright LLC

REST Web Service

JAX-RS HTTP PUT Example of REST Web Service

JAX-RS is a Java API specification that provides support in creating or developing RESTful web services. In this lesson, we will be creating a simple RESTful web service that is accessible via HTTP PUT method and is implemented via JAX-RS. It is assumed that you have went through the JAX-RS HTTP GET Example of REST Web Service before proceeding through this tutorial.

Open in your Eclipse the 'RestJumpStart' Java project and we will need to modify the 'com.rest.service.AccountService' class.

  package com.rest.service;

  import javax.ws.rs.Consumes;
  import javax.ws.rs.GET;
  import javax.ws.rs.PUT;
  import javax.ws.rs.Path;
  import javax.ws.rs.Produces;
  import javax.ws.rs.core.MediaType;

  @Path("/AccountService")
  public class AccountService {

    @GET
    @Path("/accounts")
    @Produces(MediaType.APPLICATION_XML)
    public String getAccounts(){
      return "<accounts><account><accountId>1</accountId>" 
        + "<firstName>Rolan</firstName>" 
        + "<lastName>Liwanag</lastName>" 
        + "</account></accounts>";
    }
    
    @PUT
    @Path("/accounts")
    @Consumes("application/xml")
    @Produces("application/xml")
    public String createAccount(String representation) {
      System.out.println("executing UsersResource.createUser()");
      representation 
        = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"  
        + representation;
      return representation;
    }
  }
                            

As you can see, we added a new method named 'createAccount' which accepts a 'java.lang.String' parameter and returns a 'java.lang.String' parameter. We made the method to be accessible via HTTP PUT method by adding the '@PUT' annotation on top of the method declaration. It is also important to know that we added the annotation '@Consumes("application/xml")' to indicate that it is expecting a payload which is an XML. That is in fact the variable 'representation' is, the XML payload. We also added the annotation '@Produces("application/xml")' to indicate that the web service will be returning an XML as a response. There is nothing special on the 'web.xml' file. It is still the exact same copy of what we had in the previous lesson. Just for the sake of convenience, I am placing it below.

  <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      id="WebApp_ID" version="3.0">
    <display-name>Rest Jump Start</display-name>
    <servlet>
      <servlet-name>
        Jersey RESTful Application
      </servlet-name>
      <servlet-class>
        org.glassfish.jersey.servlet.ServletContainer
      </servlet-class>
      <init-param>
        <param-name>
          jersey.config.server.provider.packages
        </param-name>
        <param-value>
          com.rest.service
        </param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>
        Jersey RESTful Application
      </servlet-name>
      <url-pattern>
        /rest/*
      </url-pattern>
    </servlet-mapping>
  </web-app>
                            

Deploy your application by copying your 'RestJumpStart' directory to your '/tomcat/webapps/' directory. Then, open a command prompt and start your Apache Tomcat application server. You can now invoke your RESTful web service by invoking it in a REST client like Postman or SOAPUI using the HTTP PUT method and the URL 'http://localhost:8080/RestJumpStart/rest/AccountService/accounts'. However, it is better for us to learn how to invoke RESTful web services programmatically using Java. Create another Java project. In your Eclipse. Name it as 'RestClientJumpstart'. Create a class and name it as 'AccountClient' and put it inside the package 'com.example.restclient'. Here is the source code for it.

  package com.example.restclient;

  import org.apache.commons.httpclient.HttpClient;
  import org.apache.commons.httpclient.HttpException;
  import org.apache.commons.httpclient.methods.PutMethod;
  import org.apache.commons.httpclient.methods.StringRequestEntity;

  public class AccountClient {

    public static void main(String[] args) {
      HttpClient client = new HttpClient();
      try {
        PutMethod put = new PutMethod("" + 
          "http://localhost:8080/RestJumpStart/rest/" 
          + "AccountService/accounts");
        System.out.println("start of POST method");
        put.setRequestEntity(new StringRequestEntity("" 
          + "ryanjaredliwanag" 
          + "","application/xml","UTF-8"));
        int statusCode = client.executeMethod(put);
        System.out.println(new String(put.getResponseBody()));
        System.out.println("end of POST method\n");
      } catch(HttpException httpe) {

      } catch (Exception e) {

      }
    }
  }

                            

Download the commons-codec-1.3.jar, commons-httpclient-3.1.jar and commons-logging-1.1.1.jar, place it on your /RestClientJumpStart/lib' directory and include the JAR files in your 'Java Build Path'.

REST Client Apache Commons


Run the client application as a 'Java Application'. You are now able to invoke a REST web service application via a Java application using the HTTP PUT method.


Back    Next