Reputation: 2354
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:
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?
Upvotes: 0
Views: 475
Reputation: 19445
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.
Upvotes: 1
Reputation: 2354
The answer was to store the output data first in a String object;
outputData = mapper.writeValueAsString(list);
Then in the servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Get Response");
ConvertCSV cleanup = new ConvertCSV();
String outputData = cleanup.cleanupData();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(outputData);
out.close();
}
Upvotes: 0