Return JSON Servlet
If you want to return back data in JSON format from servlet class please follow steps below:
Steps:
Create jsp as below where it uses jQuery to pass data and call to servlet and it returns data in JSON format:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript"> function returnJSONData() { var processData = 'JSON'; $.ajax({ type: "GET", url: "./AjaxServlet", data: "processData="+processData, success: function(result){ alert("Data type process: "+result.processData +" First Name: "+result.firstName +" Last Name: "+result.lastName) }, error: function (xhr, ajaxOptions, thrownError) { alert("Error status code: "+xhr.status); alert("Error details: "+ thrownError); } }); } </script> </head> <body> <input type="Submit" value="JSON data from servlet" onclick="returnJSONData();"> </body> </html>
Create servlet as below and return JSON data:
package com.javahonk; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Servlet implementation class AjaxServlet */ public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AjaxServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, * HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String processData = request .getParameter("processData"); response.setContentType("application/json"); response.setHeader("Cache-Control", "no-cache"); Map<String, String> personMap = new HashMap<String, String>(); if (null != processData && processData. equalsIgnoreCase("JSON")) { personMap.put("processData", processData); personMap.put("firstName", "Java"); personMap.put("lastName", "Honk"); } else { for (int i = 0; i < 5; i++) { personMap.put("firstName"+i, "Java"); personMap.put("lastName"+i, "Honk"); } } Gson gson = new GsonBuilder().setPrettyPrinting() .create(); String json = gson.toJson(personMap); response.getWriter().write(json); } /** * @see HttpServlet#doPost(HttpServletRequest request, * HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
If you want to see JSON data execute servlet from browser using servlet name you will see below sample JSON data returned from servlet:
Or deploy this you will see first jsp page below hit button you will see below sample data with java script alert message:
Return JSON Servlet