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. }  

posted on 2011-08-23 20:23  程雨轩  阅读(3673)  评论(0编辑  收藏  举报

导航