servlet中如何向页面输出json信息呢?
下文笔者讲述Servlet向浏览器输出json字符串的方法分享,如下所示
实现思路:
1.定义内容体的type为 application/json;charset=utf-8
2.向response对象中写入待输出的字符串
例:
/**
* servlet中使用json格式输出信息
* @param response
*/
protected void responseOutWithJson(HttpServletResponse response,
Object responseObject) {
//将实体对象转换为JSON Object转换
JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(responseJSONObject.toString());
logger.debug("返回是\n");
logger.debug(responseJSONObject.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


