Bright Java Tutorial

is brought to you by DoITBright LLC

REST Web Service

JAX-RS HTTP DELETE 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 DELETE 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 java.io.IOException;

  import javax.servlet.http.HttpServletResponse;
  import javax.ws.rs.Consumes;
  import javax.ws.rs.FormParam;
  import javax.ws.rs.GET;
  import javax.ws.rs.POST;
  import javax.ws.rs.PUT;
  import javax.ws.rs.Path;
  import javax.ws.rs.Produces;
  import javax.ws.rs.core.Context;
  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) {
      representation 
        = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" 
        + representation;
      return representation;
    }
    
    @POST
    @Path("/accounts")
    @Produces(MediaType.APPLICATION_XML)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public String updateAccount(
        @FormParam("accountId") int accountId,
        @FormParam("firstName") String firstName,
        @FormParam("lastName") String lastName,
        @Context HttpServletResponse servletResponse) 
        throws IOException {
      System.out.println(">>> accountId = " + accountId);
      System.out.println(">>> firstName = " + firstName);
      System.out.println(">>> lastName = " + lastName);
      return "<result>success</result>";
    }
    
    @DELETE
    @Path("/accounts/{accountId}")
    @Produces(MediaType.APPLICATION_XML)
    public String 
        deleteAccount(@PathParam("accountId") int accountId) {
      System.out.println("deleting accountId = " + accountId);
      return "<result>success</result>";
    }
  }
                            

As you can see, we added a new method named 'deleteAccount' which accepts the parameters 'int accountId' and has an annotation '@PathParam("accountId")' beside it and returns a 'java.lang.String' parameter. We made the method to be accessible via HTTP DELETE method by adding the '@DELETE' annotation on top of the method declaration. We also added the annotation '@Produces(MediaType.APPLICATION_XML)' to indicate that the web service will be returning an XML as a response. It is important to notice that the annotation '@Path("/accounts/{accountId}")' has 'accountId' surrounded by open and close curly braces. This means, we will be passing the 'accountId' parameter as part of the URL itself. 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 DELETE method and the URL 'http://localhost:8080/RestJumpStart/rest/AccountService/accounts/{accountId}' where you must replace the '{accountId}' with a valid 'accountId'. For example, accountId equal to 2, then, the URL will be 'http://localhost:8080/RestJumpStart/rest/AccountService/accounts/2'. However, it is better for us to learn how to invoke RESTful web services programmatically using Java. Using the Java project named 'RestClientJumpStart' that we created in the previous lesson JAX-RS HTTP PUT Example of REST Web Service, modify the class 'AccountClient' that is inside the package 'com.example.restclient'. Here is the full source code for it.

  package com.example.restclient;

  import javax.ws.rs.client.Client;
  import javax.ws.rs.client.ClientBuilder;
  import javax.ws.rs.client.Entity;
  import javax.ws.rs.core.Form;
  import javax.ws.rs.core.MediaType;

  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) {
	  AccountClient ac = new AccountClient();
	  ac.callPutMethod();
	  ac.callPostMethod();
	  ac.callDeleteMethod();
    }
  
    public void callPutMethod() {
      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) {

      }
    }
  
    public void callPostMethod() {
      Client client = ClientBuilder.newClient();
      Form form = new Form();
      form.param("accountId", "1");
      form.param("firstName", "Pedro");
      form.param("lastName", "Penduko");

      String callResult = 
        client.target("http://localhost:8080/RestJumpStart" 
        + "/rest/AccountService/accounts")
          .request(MediaType.APPLICATION_XML)
          .post(
            Entity.entity(
              form, 
              MediaType.APPLICATION_FORM_URLENCODED_TYPE
            ), 
            String.class
          );
      System.out.println("*** Call result = " + callResult);
    }
  }
  
  public void callDeleteMethod() {
    Client client = ClientBuilder.newClient();
    //delete accountId equal to 2
    String callResult = 
      client.target("http://localhost:8080/RestJumpStart" 
      + "/rest/AccountService/accounts")
        .path("/{accountId}")
        .resolveTemplate("accountId", 2)
        .request(MediaType.APPLICATION_XML)
        .delete(String.class);
    System.out.println("*** Call result = " + callResult);
  }
                            

If you have not finished doing this, 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'. In addition, copy all your JAR files inside the '/RestJumpStart/WEB-INF/lib' directory and paste it inside your 'RestClientJumpStart/lib' directory. Add all of these JAR files in your 'Java Build Path'.

REST Client Apache Commons And JAX-RS


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 DELETE method.


Back