Passing data between a JSP page and servlet using JSON and JQuery (part 2)

In part 1, I discussed the client side code and gave examples of how to use JSON in a web page using JavaScript.  Part 2 discusses the server side code and gives an example of how to use JSON inside a Java servlet.  I won’t spend any time in review here so if you need a refresher you can re-read part 1.

The following block of code is a stub servlet that contains the doGet() and doPost() methods.  Notice that the doPost() method simply calls the doGet() method.  This is a shortcut for convenience - you can choose to implement each method with unique behaviors if you choose.  This example application submits the form to the server using $.getJSON(), which invokes the GET HTTP request, so the doGet() method is the entry point into the servlet.

package com.windchill101.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class ExportServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

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

The first thing we want to do inside the doGet() method is to set the content type to text/json in the HttpServletResponse object so the web browser knows how to process the response once it’s returned from the server:

response.setContentType("text/json");

Since the json object is in essence just a String, we can use the PrintWriter from the response object to send the JSON object back to the browser:

 PrintWriter out = response.getWriter();

Now we can start harvesting information from the request object, including the json object and any other parameters we need.  In part 1 we sent two parameters to the server:

  1. action:”export”
  2. json:jsonData

The first parameter is a simple string and the second parameter is our json object.  Lets pull both of these values from the request object:

String action = request.getParameter("action");
String json = request.getParameter("json");

The action parameter can be used as-is since it’s a simple string.  The json parameter needs to be converted to a JSONObject before we can use it - we do this with the static JSONValue.parse() method:

JSONObject jsonDataObject = (JSONObject) JSONValue.parse(json);

At this point, we can get the variable values by invoking the get() method, passing the variable name as a parameter.  Since the JSONObject can hold objects, we need to cast the value to a String:

String ecoStatus = ((String)jsonData.get("ecoStatus"));
String emailName = ((String)jsonData.get("emailName"));
String exportFormat2D = ((String)jsonData.get("exportFormat2D"));
String exportFormat3D = ((String)jsonData.get("exportFormat3D"));
String exportSupplier = ((String)jsonData.get("exportSupplier"));
String fromDrawingNumber = ((String)jsonData.get("fromDrawingNumber"));
String toDrawingNumber = ((String)jsonData.get("toDrawingNumber"));
String partNumbers = ((String)jsonData.get("partNumbers"));

For the sake of consistency, I’m using the same variable names in this example on both ends of the transaction.  In the example above, the variable ecoStatus is used both within the jsonData object as well as in the servlet and in the JavaScript function within the web page.  On the form however, the form field name is ‘status’.  You can choose to use different names at each step, but I prefer to use consistent names.

Now that the servlet knows the form field values from the web page, it can do some processing of the data and prepare to send a message back to the page.  In this example, I’ll use another Java class named ExportModel to do the actual work.  I’m a strong believer in keeping programs modular when at all possible – it improves the maintainability of code, makes it easier to break the program up for testing, and improves my chances of reusing code for other projectes.   

ExportModel model = new ExportModel();
model.setFromDrawingNumber(fromDrawingNumber);
model.setToDrawingNumber(toDrawingNumber);
model.setEcoStatus(ecoStatus);
model.setExportFormat2D(exportFormat2D);
model.setExportFormat3D(exportFormat3D);
model.setExportSupplier(exportSupplier);
model.setEmailName(emailName);
model.processExport();
String status = model.getStatusMessage();

The ExportModel has a getStatusMessage() method that provides a human readable message that we will display on the web page so the user knows if the operation was successful.

Now we need to create a new JSONObject and add the status message so we can return it to the web page:

JSONObject result = new JSONObject();
result.put("message",status);

Now we need to convert the JSONObject to a string so we can send it back using the PrintWriter handle that we got from the response object.  The JSONObject has a static method that takes a JSONObject instance as a parameter and returns a properly formatted String object.

String jsonResult = JSONObject.toJSONString(result);

Now that we have the properly formatted JSON string, we can simply print it using the PrintWriter object “out”:

out.println(jsonResult);
out.flush();
out.close();

Here’s the complete doGet() method when everything discussed above is assembled together.  Note that I’ve added a try/catch/finally statement to handle any exceptions that may be thrown:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/json");
    PrintWriter out = response.getWriter();

    try {
        String action = request.getParameter("action");
        String json = request.getParameter("json");
        JSONObject jsonData = (JSONObject) JSONValue.parse(json);
        String fromDrawingNumber = ((String)jsonData.get("fromDrawingNumber"));
        String toDrawingNumber = ((String)jsonData.get("toDrawingNumber"));
        String ecoStatus = ((String)jsonData.get("ecoStatus"));
        String exportFormat2D = ((String)jsonData.get("exportFormat2D"));
        String exportFormat3D = ((String)jsonData.get("exportFormat3D"));
        String exportSupplier = ((String)jsonData.get("exportSupplier"));
        String partNumbers = ((String)jsonData.get("partNumbers"));
        String emailName = ((String)jsonData.get("emailName"));

        ExportModel model = new ExportModel();
        model.setFromDrawingNumber(fromDrawingNumber);
        model.setToDrawingNumber(toDrawingNumber);
        model.setEcoStatus(ecoStatus);
        model.setExportFormat2D(exportFormat2D);
        model.setExportFormat3D(exportFormat3D);
        model.setExportSupplier(exportSupplier);
        model.setPartNumbers(partNumbers);
        model.setEmailName(emailName);

        String status = "{\"message\":\"Error - action was neither 'copy' or 'export'\"}";
        if (action.equals("copy")) {
            model.processSaveAs();
            status = model.getStatusMessage();
        } else if (action.equals("export")) {
            model.processExport();
            status = model.getStatusMessage();
        }

        JSONObject result = new JSONObject();
        result.put("message",status);
        String jsonResult = JSONObject.toJSONString(result);
        out.println(jsonResult);
    } catch (Exception ex) {
        out.println("{\"message\":\"Error - caught exception in ExportServlet\"}");
    } finally {
        out.flush();
        out.close();
    }
}

That wraps up this example - I apologize for the length but there are a lot of pieces involved.  Hopefully it’s crystal clear and you will be able to use this concept in your own web application.  Feel free to leave comments or ask questions below.

26 thoughts on “Passing data between a JSP page and servlet using JSON and JQuery (part 2)

  1. Really a nice tutorial….Helped me quite a lot to understand how i should work with json and servlet….

    Thanks ,
    Great Tutorial

  2. Just found your blog.. interesting tutorial. I’m interested in the steps required to add the custom servlet from above to Windchill. Is it as simple as a servlet / servlet-mapping entry in codebase/WEB-INF/web.xml? Or is there more configuration required?

    • Yes, for tomcat add the following to web.xml to configure PDMLink to make use of your servlet. There are two tags that you’ll need to add to the web.xml file, a servlet tag and servlet-mapping tag:

      <servlet>
      <description></description>
      <display-name>ExportServlet</display-name>
      <servlet-name>exportservlet</servlet-name>
      <servlet-class>com.windchill101.example.ExportServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>exportservlet</servlet-name>
      <url-pattern>/servlet/exportservlet/*</url-pattern>
      </servlet-mapping>

  3. what is the purpose of the tag /servlet/exportservlet/*</url-pattern

    in web.xml.

    Also I have replicated the code to my local machine but still not working
    the problem isthat I will not go into the function in

    $.getJSON("exportservlet", {action:"export",json:jsonData}, function(data) {
    alert(data.message);
    $('#return_message').html(data.message);
    })

    any suggestion would be appreciated

    Cheers

  4. I have already declared my servlet in web.xml as you have shown above however I am still gettig a 404 because the getJSON function is looking for the servlet inside the same folder as the JSP and not in web.xml

    could you please help

    Thank you

  5. Im having a problem creating a jsonParser file, hence it also shows errors on my jsonValue class cos it references a method that is called in the jsonParser file

  6. Really, This helped me a lot to understand the basic concept. But can you show me a exmple in which data is coming from database into servlet and display the data in jsp

  7. hi,

    I am new to web programming.This blog is really interesting, i am running to run this codes on netbeans and tomcat , do i have to add any librarys, because i am getting errors in ExportModel, JSONobject

    Thank you

  8. I see you share interesting things here, you can earn some additional money, your blog has big
    potential, for the monetizing method, just type in google – K2 advices how to monetize a website

  9. Hello, i feel that i noticed you visited my weblog
    thus i came to return the choose?.I’m trying to in finding issues to enhance my site!I guess its ok to make use of some
    of your concepts!!

  10. I have to thank you for the efforts you’ve put in writing this blog.
    I’m hoping to view the same high-grade blog posts from you
    in the future as well. In fact, your creative writing abilities has
    encouraged me to get my own website now ;)

  11. I read a lot of interesting articles here. Probably you spend
    a lot of time writing, i know how to save you a lot of time, there is an online tool that creates readable, SEO friendly articles in minutes, just type in google – laranitas free content source

  12. HI,
    I have followed the tutorial , but the thing is i’m not getting any output. Any help is appreciated.

    Thanks,
    Devaki.

  13. Pingback: Fix Jsp Error Page Web.xml Windows XP, Vista, 7, 8 [Solved]

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>