How to Return a JSON Response from a Java Servlet

In this blog post, we'll create a simple web application and explore how to return a JSON response from a Java Servlet. We'll use the latest versions of the relevant libraries and tools to ensure our example is up-to-date.

Returning a JSON response from a Java Servlet is a common task, especially in RESTful web services.

Development Steps

  1. Create a Maven Web Application
  2. Add Maven Dependencies
  3. Create a Java POJO Entity - User.java
  4. Create Servlet and Return JSON Response - UserServlet.java
  5. Demo

Tools and Technologies Used

  • Java 11 or later
  • Servlet 6.1.0
  • GSON 2.8.8
  • IDE - Eclipse
  • Maven 3.6 +

Step 1: Create a Maven Web Application

Let's create a simple Maven web application in Eclipse IDE using this guide.

Refer to the following project structure for your reference:

Step 2: Add Maven Dependencies

Add the latest release of the required dependencies to your pom.xml file:

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.8</version>
        </dependency>
    </dependencies>

Step 3: Create a Java POJO Entity - User.java

Let’s create a User entity, which will later be returned from the Servlet as JSON:

package net.javaguides.servlet;

import java.util.Date;

public class User {

    private long id;
    private String firstName;
    private String lastName;
    private String emailId;
    private Date createdAt;
    private String createdBy;
    private Date updatedAt;
    private String updatedBy;

    public long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }
}

Step 4: Create Servlet and Return JSON Response - UserServlet.java

A quick sample for converting an object to JSON representation with Gson would be:

String userJsonString = new Gson().toJson(user);

For producing a JSON response, the content type should be application/json:

PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(userJsonString);
out.flush();

Now, let’s create UserServlet that returns a JSON response:

package net.javaguides.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Class demonstrates how to return JSON from a servlet using Gson API.
 */
@WebServlet(name = "UserServlet", urlPatterns = "/userServlet")
public class UserServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        User user = new User();
        user.setId(100L);
        user.setFirstName("Ramesh");
        user.setLastName("Fadatare");
        user.setCreatedAt(new Date());
        user.setCreatedBy("Admin");
        user.setEmailId("ramesh@gmail.com");
        user.setUpdatedAt(new Date());
        user.setUpdatedBy("Admin");

        String userJsonString = this.gson.toJson(user);

        PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(userJsonString);
        out.flush();
    }
}

Step 5: Demo

Deploy this web application in the Tomcat server and access it at: http://localhost:8080/servlet-json-example/userServlet.

Conclusion

In this tutorial, we have learned how to create a simple web application and return a JSON response from a Java Servlet using the Gson library. This approach is useful for building RESTful APIs where JSON is the standard format for data exchange.

Related Servlet Posts

Comments