Al Grant Al Grant -3 years ago 117
HTTP Question

Java webserver to respond with JSON

I am trying to create a simple java web-app that responds with a GET request to /test with a JSON string.

My environment is Java, Intellij and Tomcat 8.5.4.

So far I have 3 classes already:


  • CSV - for the CSV to JSON conversion

  • CleanUp - a class to actually convert the data

  • Servlet - a class that responds to a GET request



My Servlet class:

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 java.io.IOException;


@WebServlet(name = "Servlet")
public class Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET request received");
CleanUp cleanup = new CleanUp();
cleanup.cleanupData();

// Logic needed here to send the data to client

}
}


The CleanUp class currently sends the resulting data to console like:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, list);


I am farily new and not even sure if what I want can be done as part of javax.http.servlet or is another dependency required?

Answer Source

Your solution no doubt works for you, but in the future you may want update it as follows:

public class Cleanup {
  ...

  public void cleanupData(Writer output) {
     ObjectMapper mapper = new ObjectMapper();
     mapper.enable(SerializationFeature.INDENT_OUTPUT);
     mapper.writeValue(output, list);
  } 

  ...
}

and

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Get Response");
    response.setContentType("application/json");
    ConvertCSV cleanup = new ConvertCSV();
    String outputData = cleanup.cleanupData(response.getWriter());
    ...

Setting the content type correctly will make it easier for Javascript to process the response without it being mangled by the browser (because you told it that its HTML).

Secondly writing the JSON directly to the response will improve the scalability of your servlet because it eliminates the copy of the JSON that you're creating in the String variable. This will not make much difference if your JSON is short, but imagine if cleanupData was generating large amounts of output, such as when the list contains 1000s of entries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download