Servlet CRUD REST API - Servlet Restful Web Services Example

In this example, we will show you how to create REST APIs using JavaEE Servlet which returns JSON to the client.

We use below HttpServlet class methods to perform CRUD operations:

  • protected void doDelete(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a DELETE request.
  • protected void doGet(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a GET request.
  • protected void doPost(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a POST request.
  • protected void doPut(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a PUT request.

1. Create Maven Web Application

Use the below article to create a Maven web project in Eclipse IDE:

2. Add Maven Dependencies

Open the pom.xml file and add the following dependencies:
                <dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.5</version>
		</dependency>
		<dependency>
			<groupId>org.assertj</groupId>
			<artifactId>assertj-core</artifactId>
			<version>3.11.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

3. Create Model - Todo.java

Let's create a Todo model class that Servlet returns to the client as JSON:
public class Todo {

    private Long id;
    private String text;

    public Todo() {
    }

    public Todo(Long id, String text) {
        this.id = id;
        this.text = text;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

4. Create Static Data - Todos.java

Let's create a Todos class that creates static data:

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

public class Todos {

    public static Map<Long, Todo> todos = new HashMap<>();

    static {
        todos.put(1L, new Todo(1L, "first todo"));
        todos.put(2L, new Todo(2L, "second todo"));
    }

    public static Long nextId() {
        return todos.keySet().stream().reduce(Math::max).orElse(0L) + 1L;
    }
}

5. Create Util Class

Util class to convert Stream to String:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import static java.util.stream.Collectors.joining;

public class Util {

	public static String readInputStream(InputStream stream) {
		return new BufferedReader(new InputStreamReader(stream)).lines().collect(joining("\n"));
	}
}

6. Create Servlet - CRUD Operations

Let's create a Servlet named TodoServlet that performs CRUD operations:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static java.util.stream.Collectors.joining;

public class TodoServlet extends HttpServlet {

	private static final Gson GSON = new GsonBuilder().create();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uri = req.getRequestURI();
		Long id = Long.parseLong(uri.substring("/todos/".length()));

		String json = GSON.toJson(Todos.todos.get(id));

		resp.setStatus(200);
		resp.setHeader("Content-Type", "application/json");
		resp.getOutputStream().println(json);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uri = req.getRequestURI();
		Long id = Long.parseLong(uri.substring("/todos/".length()));

		if (Todos.todos.containsKey(id)) {
			resp.setStatus(422);
			resp.getOutputStream().println("You cannot created Todo with id " + id + " because it exists!");
		}

		String json = Util.readInputStream(req.getInputStream());
		Todo todo = GSON.fromJson(json, Todo.class);
		todo.setId(id);

		Todos.todos.put(todo.getId(), todo);

		resp.setStatus(201);
		resp.setHeader("Content-Type", "application/json");
		resp.getOutputStream().println(GSON.toJson(todo));
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uri = req.getRequestURI();
		Long id = Long.parseLong(uri.substring("/todos/".length()));

		if (!Todos.todos.containsKey(id)) {
			resp.setStatus(422);
			resp.getOutputStream().println("You cannot update Todo with id " + id + " because it doesn't exists!");
		}

		String json = Util.readInputStream(req.getInputStream());
		Todo todo = GSON.fromJson(json, Todo.class);
		todo.setId(id);

		Todos.todos.put(todo.getId(), todo);

		resp.setStatus(200);
		resp.setHeader("Content-Type", "application/json");
		resp.getOutputStream().println(GSON.toJson(todo));
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uri = req.getRequestURI();
		Long id = Long.parseLong(uri.substring("/todos/".length()));

		Todo todo = Todos.todos.remove(id);
		String json = GSON.toJson(todo);

		resp.setStatus(200);
		resp.setHeader("Content-Type", "application/json");
		resp.getOutputStream().println(json);
	}
}
  • protected void doDelete(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a DELETE request.
  • protected void doGet(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a GET request.
  • protected void doPost(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a POST request.
  • protected void doPut(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a PUT request.

7. Configure Servlet in Web.xml

Now let's configure Servlet in web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
		PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
		"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
	<servlet>
		<servlet-name>TodoServlet</servlet-name>
		<servlet-class>com.sourcecodeexamples.rest.TodoServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>TodoServlet</servlet-name>
		<url-pattern>/todos/*</url-pattern>
	</servlet-mapping>
</web-app>
Run in this project in Tomcat server and Test all the APIs using /todos URL.

Comments