How to Create a Simple Servlet to Handle JSon Requests

On this example, im trying to create a simple servlet to handle JSon request. Im using this servlet to handle JSon request from my front end such as web or even desktop application. Thanks to GSon library, it really helped on simplifying javabean convert to json strings and the other way around.

First as usual, a simple java bean to handle request and response format

package com.edw.bean;

public class Student {
 
    private String name;
    private int age;
    private byte gender;

	// other setter and getter
}
package com.edw.bean;

public class Status {
    private boolean success;
    private String description;
	
	// other setter and getter
}

And this is my servlet,

package com.edw.servlet;

import com.edw.bean.Status;
import com.edw.bean.Student;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonParserServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");        
        Gson gson = new Gson();

        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }

            Student student = (Student) gson.fromJson(sb.toString(), Student.class);

            Status status = new Status();
            if (student.getName().equalsIgnoreCase("edw")) {
                status.setSuccess(true);
                status.setDescription("success");
            } else {
                status.setSuccess(false);
                status.setDescription("not edw");
            }
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            Status status = new Status();
            status.setSuccess(false);
            status.setDescription(ex.getMessage());
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } 
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is a screenshot on how my message actually look like

Have Fun (H)

10 thoughts on “How to Create a Simple Servlet to Handle JSon Requests”

  1. Now, looking the method fromJson from GSon class, I saw that it accepts a Reader as parameter. So, instead to read the lines and append then to a BufferedReader, you can just do:
    Student student = gson.fromJson(request.getReader(), Student.class);

    Another, tip:
    You don’t need to cast the result to Student, ’cause it knows the type – from the second parameter.

    Regards,
    Marcio Wesley Borges

  2. Hi, i kinda understand what your servlet does. But i am confused as how from the client to make the request? Any help given is really appreciated. I am stuck right now as I am doing a project in which I am just about to learn bout JSON. Thank you so much.

  3. Hi there…i have did what u had posted. I am confused and stuck as how u will request from the client side? Could u help me pls? Thank you?

Leave a Reply to Marcio Wesley Borges Cancel Reply

Your email address will not be published.