Jersey CRUD RESTful webservice Tutorial with examples

This section creates a CRUD (Create, Read, Update, Delete) restful web service. It will allow to maintain a list of Tasks in your web application via HTTP calls.

Jersey CRUD RESTful webservice

STEP 1 : Create a new dynamic project called TutorialsDesk.Rest.CRUDWebServices and add the Jersey libs.

STEP 2 : Change the web.xml file to the following.

<?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>TutorialsDesk.RestHelloWorld</display-name>
 <servlet>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
     <!-- Register resources and providers under com.tutorialsdesk.rest.helloworld package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.tutorialsdesk.rest.resources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 


STEP 3 : Create the following task.java data model and a Singleton which serves as the data provider for the model. We use the implementation based on an enumeration. The Task class is annotated with a JAXB annotation.

package com.tutorialsdesk.rest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Task {
  private String id;
  private String summary;
  private String description;
  
  public Task(){
    
  }
  public Task (String id, String summary){
    this.id = id;
    this.summary = summary;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }
  
  
} 



STEP 4 : Create the following TaskDao.java as below.

package com.tutorialsdesk.rest.dao;

import java.util.HashMap;
import java.util.Map;

import com.tutorialsdesk.rest.model.Task;;

public enum TaskDao {
  instance;
  
  private Map<String, Task> contentProvider = new HashMap<String, Task>();
  
  private TaskDao() {
    
    Task task = new Task("1", "Learn REST");
    task.setDescription("Read http://www.tutorialsdesk.com/2014/09/jersey-restful-webservices-tutorial.html");
    contentProvider.put("1", task);
    task = new Task("2", "Do something");
    task.setDescription("Read complete http://www.tutorialsdesk.com");
    contentProvider.put("2", task);
    
  }
  public Map<String, Task> getModel(){
    return contentProvider;
  }
  
} 



STEP 5 : Create a simple HTML form .
The REST service can be used via HTML forms. The following HTML form will allow to post new data to the service. Create the following page called create_task.html in the WebContent folder.

<!DOCTYPE html>
<html>
 <head>
  <title>Form to create a new resource</title>
 </head>
<body>
  <form action="../TutorialsDesk.Rest.CRUDWebServices/rest/tasks" method="POST">
  <label for="id">ID</label>
  <input name="id" />
  <br/>
  <label for="summary">Summary</label>
  <input name="summary" />
  <br/>
  Description:
  <TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
  <br/>
  <input type="submit" value="Submit" />
  </form>
</body>
</html> 



STEP 6 : Create the following TaskResource.java class which will be used as REST resources .
package com.tutorialsdesk.rest.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.tutorialsdesk.rest.dao.TaskDao;
import com.tutorialsdesk.rest.model.Task;

public class TaskResource {
  @Context
  UriInfo uriInfo;
  @Context
  Request request;
  String id;
  public TaskResource(UriInfo uriInfo, Request request, String id) {
    this.uriInfo = uriInfo;
    this.request = request;
    this.id = id;
  }
  
  //Application integration     
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Task getTodo() {
    Task task = TaskDao.instance.getModel().get(id);
    if(task==null)
      throw new RuntimeException("Get: Task with " + id +  " not found");
    return task;
  }
  
  // for the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public Task getTodoHTML() {
    Task task = TaskDao.instance.getModel().get(id);
    if(task==null)
      throw new RuntimeException("Get: Task with " + id +  " not found");
    return task;
  }
  
  @PUT
  @Consumes(MediaType.APPLICATION_XML)
  public Response putTodo(JAXBElement<Task> task) {
    Task c = task.getValue();
    return putAndGetResponse(c);
  }
  
  @DELETE
  public void deleteTodo() {
    Task c = TaskDao.instance.getModel().remove(id);
    if(c==null)
      throw new RuntimeException("Delete: Task with " + id +  " not found");
  }
  
  private Response putAndGetResponse(Task task) {
    Response res;
    if(TaskDao.instance.getModel().containsKey(task.getId())) {
      res = Response.noContent().build();
    } else {
      res = Response.created(uriInfo.getAbsolutePath()).build();
    }
    TaskDao.instance.getModel().put(task.getId(), task);
    return res;
  }
  
  

} 


STEP 7 : Create the following TasksResource.java class which will be used as REST resources .
package com.tutorialsdesk.rest.resources;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

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.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.tutorialsdesk.rest.dao.TaskDao;
import com.tutorialsdesk.rest.model.Task;;


// Will map the resource to the URL tasks
@Path("/tasks")
public class TasksResource {

  // Allows to insert contextual objects into the class, 
  // e.g. ServletContext, Request, Response, UriInfo
  @Context
  UriInfo uriInfo;
  @Context
  Request request;


  // Return the list of tasks to the user in the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public List<Task> getTodosBrowser() {
    List<Task> tasks = new ArrayList<Task>();
    tasks.addAll(TaskDao.instance.getModel().values());
    return tasks; 
  }
  
  // Return the list of tasks for applications
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public List<Task> getTasks() {
    List<Task> tasks = new ArrayList<Task>();
    tasks.addAll(TaskDao.instance.getModel().values());
    return tasks; 
  }
  
  
  // retuns the number of tasks
  // use http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/count
  // to get the total number of records
  @GET
  @Path("count")
  @Produces(MediaType.TEXT_PLAIN)
  public String getCount() {
    int count = TaskDao.instance.getModel().size();
    return String.valueOf(count);
  }
  
  @POST
  @Produces(MediaType.TEXT_HTML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public void newTask(@FormParam("id") String id,
      @FormParam("summary") String summary,
      @FormParam("description") String description,
      @Context HttpServletResponse servletResponse) throws IOException {
    Task task = new Task(id,summary);
    if (description!=null){
      task.setDescription(description);
    }
    TaskDao.instance.getModel().put(id, task);
    
    servletResponse.sendRedirect("../create_task.html");
  }
  
  
  // Defines that the next path parameter after tasks is
  // treated as a parameter and passed to the TodoResources
  // Allows to type http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/1
  // 1 will be treaded as parameter tasks and passed to TaskResource
  @Path("{task}")
  public TaskResource getTask(@PathParam("task") String id) {
    return new TaskResource(uriInfo, request, id);
  }
  
} 


This TasksResource uses the @PathParam annotation to define that the id is inserted as parameter.

Run Your CRUD Web Services : Run you web application in Eclipse and test the availability of your REST service under:
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks
You should see the XML representation of your TASK items.

To see the count of Task items use
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/count
to see an exiting Task use
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/{id},
e.g., http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/1
to see the Task with ID 1.
We currently have only Tasks with the ids 1 and 2, all other requests will result in an HTTP error code.

Please note that with the browser you can only issue HTTP GET requests. In The next posts we will use the Jersey client libraries to issue get, post and delete.
Jersey CRUD RESTful webservice Tutorial with examples

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Web Services in java.

Hope we are able to explain you Jersey CRUD RESTful webservices Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.