JSON,Servlet,JSP [英] JSON, Servlet, JSP
问题描述
首先,我通过URL进行的HTTP POST接受4个参数. (参数1,参数2,参数3,参数4).
Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
我可以从数据库传递参数吗?
Can I pass the parameters from the database?
输入URL后,返回的信息将使用JSON以文本格式显示 格式.
Once the URL is entered, the information returned will be in text format using JSON format.
JSON将返回{"Status":"Yes"}或{"Status":"No"}
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
如何在servlet中执行此操作? doPost()
How shall I do this in servlets? doPost()
推荐答案
只需设置适当的内容类型和编码,然后将JSON字符串相应地写入响应即可.
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
您可以考虑使用现有的JSON库来简化Java中的JSON(反序列化)工作,而不是自己编写JSON.例如 Google Gson .
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
这篇关于JSON,Servlet,JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!