2010-10-26 30 views
2

首先,我通过URL的HTTP POST接受4个参数。 (参数1,参数2,参数3,参数4)。JSON,Servlet,JSP

我可以从数据库传递参数吗?

输入URL后,返回的信息将使用JSON 格式的文本格式。

的JSON将返回{“状态”:“是”}或{“状态”:“否”}

我怎能在Servlet中做到这一点? doPost()

+0

“从数据库传递参数”? – 2010-10-26 02:44:01

回答

2

只需设置适当的内容类型和编码并相应地将JSON字符串写入响应。

String json = "{\"status\": \"Yes\"}"; 
response.setContentType("application/json"); 
response.setCharacterEncoding("UTF-8"); 
response.getWriter().write(json); 

您可以考虑使用现有的JSON库来缓解JSON(德)序列化Java中的作业,而不是自己编写JSON。例如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) 
0

Jackson是JSON对象编组的另一个选项。