How to Return a JSON Response from a Java Servlet

In this post, we’ll create a small web application and explore how to return a JSON response from a Java Servlet.

Development Steps

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

Tools and Technologies Used

  1. Java 1.8 or later
  2. Servlet 4+
  3. GSON 2.8.2
  4. IDE - Eclipse
  5. Maven 3.5 +

1. Create a Maven Web Application

Let's create a simple maven web application in eclipse IDE using https://www.javaguides.net/2018/11/how-to-create-web-project-using-maven-in-eclipse.html article.
Refer following project structure for your reference:

2. Add Maven Dependencies

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides</groupId>
    <artifactId>servlet-examples</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>servlet-examples Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>servlet-examples</finalName>
    </build>
</project>

3. Creating 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;
    }
}

4. Creating Servlet and Return JSON Response - UserServlet.java

A quick sample for converting an object to JSON representation with Gson would be:
String employeeJsonString = new Gson().toJson(employee);
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 javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

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

    private static final long serialVersionUID = 1 L;

    private Gson gson = new Gson();

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

        User user = new User();
        user.setId(100 L);
        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();
    }
}

5. Demo

Let's deploy this web application in tomcat server and hit this link in browser: http://localhost:8080/servlet-examples/userServlet

Related Servlet Posts

Comments