轉自博文:《Response JSON數據返回》http://blog.csdn.net/anialy/article/details/8665471
簡述:
在servlet填充Response的時候,做JSON格式的數據轉換
使用的類是net.sf.json.JSONObject,傳入response對象和返回的顯示類,修改response,返回前台JSON格式數據
代碼:
- /**
- * 以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();
- }
- }
- }
例如:
try {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String selectName = new String(request.getParameter("selectName").getBytes("iso-8859-1"),"utf-8");//用request獲取URL傳遞的中文參數,防止亂碼
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
if (!selectName.equals("")) {
historyEvent = historyEventService.getHistoryEventByName(projectId, selectName);//獲取對象
response.setContentType("application/json; charset=utf-8");
JSONObject responseJSONObject = JSONObject.fromObject(historyEvent); //將實體對象轉換為JSON Object轉換
out.print(responseJSONObject.toString());
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}