[英]Java servlets return JSON in synchronous HTTP requests
For all HTTP requests (synchronous and asynchronous), I would like my Java servlets to return JSON consistently to the client-side. 对于所有HTTP请求(同步和异步),我希望Java servlet将JSON一致地返回到客户端。 In this way, I can push all my presentation logic to the client side (html/css/js) and minimize JSP tags on my HTML. 这样,我可以将所有表示逻辑推到客户端(html / css / js)并最小化HTML上的JSP标签。
I understand how servlets handle Ajax requests. 我了解servlet如何处理Ajax请求。 But I'm not sure what is the best technique for returning JSON in synchronous requests. 但是我不确定在同步请求中返回JSON的最佳技术是什么。 So I did a working example of how servlets can embed JSON in HTML. 因此,我做了一个工作示例,说明servlet如何将JSON嵌入HTML。
Are there drawbacks with the following method? 以下方法是否有缺点? How can this method be improved? 如何改进这种方法?
Working Example 工作实例
Servlet (in the doGet method body) Servlet(在doGet方法主体中)
req.setAttribute("json", gson.toJson(article));
RequestDispatcher view = req.getRequestDispatcher("/WEB-INF/show.jsp");
view.forward(req, resp);
JSP JSP
<script>
var json = ${json};
alert(JSON.stringify(json));
</script>
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. 我从事Java servlet已有很长时间了,但是我认为如果将响应对象中的MIME类型设置为“ application / json”,它应该可以工作。
I Hope this post would be helpful to you. 希望这篇文章对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.