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?
- 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.
- Dispatches to the jsp (“forwarding to a view”).
- 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>