Response返回JSON數據到前台頁面


轉自博文:《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();
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM