开发者

JSON, Servlet, JSP

开发者 https://www.devze.com 2023-01-21 18:42 出处:网络
Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4). Can I pass the parameters from the database?

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).

Can I pass the parameters from the database?

Once the URL is entered, the information returned will be in text form开发者_JAVA百科at using JSON format.

The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}

How shall I do this in servlets? doPost()


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);

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)


Jackson is another option for JSON object marshalling.

0

精彩评论

暂无评论...
验证码 换一张
取 消