Response返回JSON資料到前台頁面

來源:互聯網
上載者:User

標籤:

轉自博文:《Response JSON資料返回》http://blog.csdn.net/anialy/article/details/8665471

簡述:

在servlet填充Response的時候,做JSON格式的資料轉換

使用的類是net.sf.json.JSONObject,傳入response對象和返回的顯示類,修改response,返回前台JSON格式資料


代碼:

  1. /** 
  2.  * 以JSON格式輸出 
  3.  * @param response 
  4.  */  
  5. protected void responseOutWithJson(HttpServletResponse response,  
  6.         Object responseObject) {  
  7.     //將實體物件轉換為JSON Object轉換  
  8.     JSONObject responseJSONObject = JSONObject.fromObject(responseObject);  
  9.     response.setCharacterEncoding("UTF-8");  
  10.     response.setContentType("application/json; charset=utf-8");  
  11.     PrintWriter out = null;  
  12.     try {  
  13.         out = response.getWriter();  
  14.         out.append(responseJSONObject.toString());  
  15.         logger.debug("返回是\n");  
  16.         logger.debug(responseJSONObject.toString());  
  17.     } catch (IOException e) {  
  18.         e.printStackTrace();  
  19.     } finally {  
  20.         if (out != null) {  
  21.             out.close();  
  22.         }  
  23.     }  

例如:

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

Response返回JSON資料到前台頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.