简体   繁体   English

Java Servlet在同步HTTP请求中返回JSON

[英]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? 如何改进这种方法?

  1. Servlet saves data in JSON format as a request attribute, which will then be written to the HTML document by JSP . Servlet将数据以JSON格式保存为请求属性,然后由JSP将其写入HTML文档 JSON is stored in a JavaScript variable on the HTML document. JSON存储在HTML文档的JavaScript变量中。
  2. Dispatches to the jsp ( “forwarding to a view” ). 调度到jsp( “转发到视图” )。
  3. Custom JavaScript takes the data from the embedded JSON in the HTML document and displays it. 自定义JavaScript从HTML文档中嵌入的JSON中获取数据并显示出来。

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. 希望这篇文章对您有所帮助。

JSON response is returning as text JSON响应以文本形式返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM