蓝光视频:Struts2返回XML,JSON格式

来源:百度文库 编辑:九乡新闻网 时间:2024/05/05 00:01:50
Java代码 ',1)"> 
Struts2返回XML格式
1.struts.xml里面的配置package extends="struts-default"
Java代码 ',2)"> 



2.Action里面的方法
Java代码 ',3)"> 
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里面的方法
Java代码 ',4)"> 
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,
如:
Java代码 ',5)"> 
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;
}