zoukankan      html  css  js  c++  java
  • Struts2返回XML,JSON格式

    Java代码  收藏代码
    1.   

    Struts2返回XML格式 
    1.struts.xml里面的配置package extends="struts-default" 

    Java代码  收藏代码
    1. <action name="actionName" class="bookTypeAction" method="methodName" >  
    2.         <result name="xmlMessage" type="plaintext"></result>  
    3. </action>  



    2.Action里面的方法 

    Java代码  收藏代码
    1. public void xxxMethod() throws IOException{     
    2.      HttpServletResponse response = ServletActionContext.getResponse();         
    3.      PrintWriter out = response.getWriter();         
    4.      response.setContentType("application/xml;charset=UTF-8");  
    5.      out.write("XML文档");  
    6. }  



    Struts2返回Json格式 
    1.下载jsonplugin-0.7.jar包 
    如果用JSONObject把Object转成JSON字符串的话需要下载下面的包 
       commons-beanutils-1.7.0.jar 
       json-lib-2.2.1-jdk15.jar 
       ezmorph-1.0.4.jar 
    2.Action里面的方法 
      

    Java代码  收藏代码
    1. HttpServletRequest request =ServletActionContext.getRequest();  
    2. HttpServletResponse response = ServletActionContext.getResponse();  
    3.   
    4. int bookTypeId = Integer.parseInt(request.getParameter("bookTypeId"));  
    5. int num = admimService.getDeleteBookTypeCond(bookTypeId);  
    6. response.setContentType(ContentType_JSON);  
    7. if(num == 0){  
    8.   boolean isSuccess = true;  
    9.   int x = admimService.deleteBookType(bookTypeId);  
    10.   //这是产生简单的json的方法  
    11.   response.getWriter().write("{success:"+isSuccess+",num:"+num+"}");  
    12. }else{  
    13.  response.getWriter().write("{success:false,num:"+num+"}");   
    14. }  


    如果要把一个对象的实例转成json,建议用JSONObject, 
    如: 

    Java代码  收藏代码
    1. import net.sf.json.JSONArray;  
    2. import net.sf.json.JSONObject;  
    3.   
    4. ...  
    5. ...  
    6. ...  
    7. /** 
    8.  * 通过bean生成JSON数据 
    9.  * @param bean bean对象 
    10.  * @return 生成的JSON数据 
    11. */  
    12. public static String getJsonFromBean(Object bean){  
    13.  try{  
    14.       JSONObject JsonObject = JSONObject.fromObject(bean);  
    15.       return JsonObject.toString();  
    16.  }catch(Exception e){  
    17.    e.printStackTrace();  
    18.  }  
    19.  return null;  
    20. }  
  • 相关阅读:
    gray-code——找规律
    [LeetCode] Decode Ways 解码方法个数、动态规划
    操作系统之面试常考(转)
    国内90%以上的 iOS 开发者,对 APNs 的认识都是错的
    vim配置为IDE环境(超详细,极力推荐 git)
    curl的使用(from 阮一峰)
    图片鉴黄服务提供商
    转: 【理念篇】关于数据驱动运维的几点认识
    业务调度链的染色数据上报和关联
    ITIL的考核管理体系
  • 原文地址:https://www.cnblogs.com/yuxuan/p/2151185.html
Copyright © 2011-2022 走看看