Java代碼
Struts2返回XML格式
1.struts.xml里面的配置package extends="struts-default"
Java代碼
<action name="actionName" class="bookTypeAction" method="methodName" >
<result name="xmlMessage" type="plaintext"></result>
</action>
2.Action里面的方法
Java代碼
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轉(zhuǎn)成JSON字符串的話需要下載下面的包
commons-beanutils-1.7.0.jar
json-lib-2.2.1-jdk15.jar
ezmorph-1.0.4.jar
2.Action里面的方法
Java代碼
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);
//這是產(chǎn)生簡單的json的方法
response.getWriter().write("{success:"+isSuccess+",num:"+num+"}");
}else{
response.getWriter().write("{success:false,num:"+num+"}");
}
如果要把一個對象的實例轉(zhuǎn)成json,建議用JSONObject,
如:
Java代碼
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
...
...
...
/**
* 通過bean生成JSON數(shù)據(jù)
* @param bean bean對象
* @return 生成的JSON數(shù)據(jù)
*/
public static String getJsonFromBean(Object bean){
try{
JSONObject JsonObject = JSONObject.fromObject(bean);
return JsonObject.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}