AJAX jQuery Servlet JSON XML

AJAX jQuery Servlet JSON XML

This demo will show you how to make AJAX call to servlet using jQuery. We will send and test data in both format:

  • JSON: Process data from server in JSON format
  • XML: Process data from server in XML format

Below are needed:

  • Eclipse 3.2 or above (Download from here) – Note for this demo we have used eclipse Kepler
  • JDK 1.6 or above (Download from here )
  • Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse )
  • Google gson-2.2.2 jar which we have used to convert object in JSON format (jar is already included in project)
  • JQuery js file (Links are already included in jsp page you don’t need to download anything)
  • Note: All codes are available for download in the bottom of the page

 

Steps:

  • Create dynamic web project name AJAXjQueryServlet in eclipse (Please use this link if you are not familiar how to create dynamic web project in eclipse: create dynamic web project)
  • Below shows project structure:

AJAX jQuery Servlet JSON XML

  • Copy below XML into your web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>AJAXjQueryServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>    
  </welcome-file-list>
</web-app>

 

  • Create jsp file name: index.jsp inside WebContent folder and copy paste below code:
<%@ 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 passDataUsingJQueryAJAXInXML()
    {
        var firstName = $("#firstName").val();
        var LastName = $("#lastName").val(); 
        var processData = 'XML'; 
          $.ajax({  
            type: "GET",  
            url: "./JQueryServlet",  
            data: "firstName="+firstName+"&lastName="
                    +LastName+"&processData="+processData,  
            success: function(result){
              var firstName = $(result).find('firstName').text();
              var lastName = $(result).find('lastName').text();
              alert("First Name: "+ firstName+"  Last Name: "
                      +lastName);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Error status code: "+xhr.status);
                alert("Error details: "+ thrownError);
            }
          }); 

    }
    
    function passDataUsingJQueryAJAXInJSON()
    {
        var firstName = $("#firstName").val();
        var LastName = $("#lastName").val(); 
        var processData = 'JSON'; 
          $.ajax({  
            type: "GET",  
            url: "./JQueryServlet",  
            data: "firstName="+firstName+"&lastName="
                    +LastName+"&processData="+processData,  
            success: function(result){
              var firstName = result.firstName;
              var lastName = result.lastName;
              alert("First Name: "+ firstName+"  Last Name: "
                      +lastName);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Error status code: "+xhr.status);
                alert("Error details: "+ thrownError);
            }
          }); 

    }
        

</script>
</head>
<body>

First Name: <input type="text" value="" id="firstName"><br>
Last Name: <input type="text" value="" id="lastName"><br><br>
<input type="Submit" value="Process XML data AJAX" 
            onclick="passDataUsingJQueryAJAXInXML();">
<input type="Submit" value="Process JSON data AJAX" 
            onclick="passDataUsingJQueryAJAXInJSON();">

</body>
</html>

 

  • Create package name com.javahonk inside src folder
  • Create class name: JQueryServlet.java inside com.javahonk pakcage and copy paste below content in it:
package com.javahonk;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
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;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class JQueryServlet
 */
@WebServlet("/JQueryServlet")
public class JQueryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JQueryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, 
     * HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, 
            HttpServletResponse response) 
                    throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String processData = request.getParameter("processData");
        
        if (processData.equalsIgnoreCase("XML")) {
            response.setContentType("text/xml");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write("<details>");
            response.getWriter().write("<firstName>"
                                +firstName+"</firstName>");
            response.getWriter().write("<lastName>"
                                +lastName+"</lastName>");
            response.getWriter().write("</details>");
        } else {
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-cache");
            Map<String, String> personMap = 
                    new HashMap<String, String>();
            personMap.put("firstName", firstName);
            personMap.put("lastName", lastName);
            
            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
    }

}

 

  • Now lets run this set up in tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server as below:

AJAX jQuery Servlet JSON XML

 

  • Finally you will see below screen with input box and two separate button to process data in XML and JSON forma. Enter data in input box click button to test it:

AJAX jQuery Servlet JSON XML

  • Process XML data AJAX output:

AJAX jQuery Servlet JSON XML

 

  • Process JSON data AJAX output:

AJAX jQuery Servlet JSON XML

 

download Download Project:  AJAXjQueryServlet

That’s it AJAX jQuery Servlet JSON XML

Leave a Reply

Your email address will not be published. Required fields are marked *