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)

Google+

10 Comments

Marcio Wesley Borges

about 5 years ago

Thanks for the sample. It helps me.

Reply

edwin

about 5 years ago

Hi Marcio, glad it could help :)

Marcio Wesley Borges

about 5 years ago

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

Reply

edwin

about 5 years ago

Hey, i think you are right, Thanks for the hint bro :D

Hanz

about 4 years ago

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.

Reply

edwin

about 4 years ago

Hi Hanz, try to read my other article, http://edwin.baculsoft.com/2011/10/a-simple-json-requestor-using-java/

Hanz

about 4 years ago

Sorry my email is rushh05@gmail.com

Reply

edwin

about 4 years ago

Hi Hanz, thank you for your email :)

Farhan

about 4 years ago

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?

Reply

edwin

about 4 years ago

Hi Farhan, you can find on my previous article, http://edwin.baculsoft.com/2011/10/a-simple-json-requestor-using-java/

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)