0

For all HTTP requests (synchronous and asynchronous), I would like my Java servlets to return JSON consistently to the client-side. In this way, I can push all my presentation logic to the client side (html/css/js) and minimize JSP tags on my HTML.

I understand how servlets handle Ajax requests. But I'm not sure what is the best technique for returning JSON in synchronous requests. So I did a working example of how servlets can embed JSON in HTML.

Are there drawbacks with the following method? How can this method be improved?

  1. Servlet saves data in JSON format as a request attribute, which will then be written to the HTML document by JSP. JSON is stored in a JavaScript variable on the HTML document.
  2. Dispatches to the jsp (“forwarding to a view”).
  3. Custom JavaScript takes the data from the embedded JSON in the HTML document and displays it.

Working Example

Servlet (in the doGet method body)

req.setAttribute("json", gson.toJson(article));
RequestDispatcher view = req.getRequestDispatcher("/WEB-INF/show.jsp");
view.forward(req, resp);

JSP

<script>
    var json = ${json};
    alert(JSON.stringify(json));
</script>
Community
  • 1
  • 1
ruhong
  • 1,793
  • 5
  • 28
  • 34

1 Answers1

0

Its been a long time I have worked on java servlets but i think if you set the MIME type in response object to "application/json", it should work.

I Hope this post would be helpful to you.

JSON response is returning as text

Community
  • 1
  • 1
here4learn
  • 203
  • 2
  • 9