zoukankan      html  css  js  c++  java
  • 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("返回是 ");  
    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();
            }

  • 相关阅读:
    用localeCompare实现中文排序
    点击一个链接同时打开两个页面
    汉字和Unicode编码互转
    javascript中document学习
    javascript页面表格排序
    JavaScript 仿LightBox内容显示效果
    JavaScript面向对象的简单介绍
    JavaScript键盘上下键的操作(选择)
    关于clientWidth、offsetWidth、clientHeight、offsetHeigh
    动态(按需)加载js和css文件
  • 原文地址:https://www.cnblogs.com/limeiky/p/5851836.html
Copyright © 2011-2022 走看看