日期:2014-05-16  浏览次数:20372 次

Struts2返回XML,JSON格式
Struts2返回XML格式 
1.struts.xml里面的配置package extends="struts-default"
<action name="actionName" class="bookTypeAction" method="methodName" >
        <result name="xmlMessage" type="plaintext"></result>
</action>


2.Action里面的方法
public void xxxMethod() throws IOException{   
     HttpServletResponse response = ServletActionContext.getResponse();       
     PrintWriter out = response.getWriter();       
     response.setContentType("application/xml;charset=UTF-8");
     out.write("XML文档");
}


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里面的方法
 
HttpServletRequest request =ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();

int bookTypeId = Integer.parseInt(request.getParameter("bookTypeId"));
int num = admimService.getDeleteBookTypeCond(bookTypeId);
response.setContentType(ContentType_JSON);
if(num == 0){
  boolean isSuccess = true;
  int x = admimService.deleteBookType(bookTypeId);
  //这是产生简单的json的方法
  response.getWriter().write("{success:"+isSuccess+",num:"+num+"}");
}else{
 response.getWriter().write("{success:false,num:"+num+"}");	
}

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

...
...
...
/**
 * 通过bean生成JSON数据
 * @param bean bean对象
 * @return 生成的JSON数据
*/
public static String getJsonFromBean(Object bean){
 try{
      JSONObject JsonObject = JSONObject.fromObject(bean);
      return JsonObject.toString();
 }catch(Exception e){
   e.printStackTrace();
 }
 return null;
}