Sending json response from servlet using gson

We already know how to create simple projects with netbeans see project creating with maven and creating simple web project in netbeans.

Here we want to send json data response from servlet.
Here a link is available in jsp page on link click it is calling /jsonResponse url where JsonResponse’s doGet() method is get called.

How to set HttpServletResponse set body json is as below

To generate json response we are setting response.setContentType("application/json"); that is used to set response as application/json.

Here response is reference variable of HttpServletResponse.

In servlet student object is created with name gender mobile number and three subjects marks. After creating object we are converting objects to json using gson library.

Project Explorer



This file contains a link on click that will goto /jsonResponse url

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>

Getting request from index.jsp page following code is executed.

response.setContentType(“application/json”); is used to send response as json.

response.setCharacterEncoding(“utf-8”); is character encoding method.

We have created student object which contains students id,name,gender,address, mobileNo and set of subjects and address.

We send this data to jsp using Gson Object.

The method gson.toJson(student); is converting objet to json string

then we are passing json data to PrintWriter object to write in browser



This is index.jsp page after running the project on click on link it will show json data in browser



Downlaod above program from here