我有一个动态Web项目,在我的JSP页面中,当点击表单时,它会从elasticsearch检索数据,并以适当的JSON格式作为键值对在UI中显示。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String end = request.getParameter("end");
String line1;
StringBuffer jsonString1 = new StringBuffer();
try {
URL url1 = new URL("http://localhost:9200/indexname/_search?filter_path=hits.hits._source&pretty=1&size=100000");
String payload1 = "{\"query\":{\"filtered\":{\"filter\":{\"range\":{\"Date\":{\"lte\":\""+end+"\",\"gte\":\""+start+"\"}}}}},\"_source\":{\"include\":[\"ID\",\"Name\",\"Status\",\"Date\"]}}";
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setDoInput(true);
connection1.setDoOutput(true);
connection1.setRequestMethod("POST");
connection1.setRequestProperty("Accept", "application/json");
connection1.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1.write(payload1);
writer1.close();
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = br1.readLine()) != null) {
jsonString1.append(line1);
}
br1.close();
file1.close();
connection1.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
response.setContentType("application/json");
// JSONObject jsonObj = new JSONObject(jsonString1.toString()); //JSONObject cannot be resolved to a type error is getting displayed.
//System.out.println("---------------------------");
// System.out.println(jsonObj);
PrintWriter out = response.getWriter();
out.print(jsonString1); //Here instead of String buffer I want to send a json object or an arraylist which outputs just the key value pair by removing all unwanted characters.
out.flush();
out.close();
}
在我的HTML中,执行提交操作后,它会显示类似于以下内容的结果:
{ "hits" : { "hits" : [ { "_source":{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"} }, { "_source":{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"} }, { "_source":{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"} }, { "_source":{"ID":"126","Status":"false","Name":"TYT_333","Date":"2010-08-16T12:06:48"} }, { "_source":{"ID":"127","Status":"false","Name":"CVF_230","Date":"2010-08-16T12:07:18"} }, { "_source":{"ID":"128","Status":"true","Name":"AWE_101","Date":"2010-08-16T12:03:48"} }, { "_source":{"ID":"129","Status":"true","Name":"WEC_299","Date":"2010-08-16T12:07:29"} } ] }}
相反,我想在我的用户界面中显示一些警报框或类似的东西,以显示
{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"},
{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"},
{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"}
有什么想法可以帮我实现这个吗?请给予建议。谢谢。
org.json
是一种不错的方法来实现这个功能。如果你遇到了错误,尝试将它的二进制文件添加到你的JSP类路径中。这应该可以解决问题。 - Top Sekret