package org.masque.ztree.demo.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.masque.ztree.demo.vo.ZtreeVo;
import com.opensymphony.xwork2.ActionSupport;
public class JsonTest extends ActionSupport implements ServletRequestAware, ServletResponseAware{
/**
*
*/
private static final long serialVersionUID = 1L;
protected HttpServletRequest request;
protected HttpServletResponse response;
public String getList() {
String id = request.getParameter("id");
String name = request.getParameter("name");
List l = new ArrayList();
if (StringUtils.isEmpty(id)||StringUtils.isEmpty(name)) {
ZtreeVo ztreeVo1 = new ZtreeVo("1", "测试1", true);
ZtreeVo ztreeVo2 = new ZtreeVo("2", "测试2", true);
ZtreeVo ztreeVo3 = new ZtreeVo("3", "测试3", true);
ZtreeVo ztreeVo4 = new ZtreeVo("4", "测试4", true);
l.add(ztreeVo1);
l.add(ztreeVo2);
l.add(ztreeVo3);
l.add(ztreeVo4);
}else{
ZtreeVo ztreeVo1 = new ZtreeVo(id+"_1", "测试"+id+"_1", true);
ZtreeVo ztreeVo2 = new ZtreeVo(id+"_2", "测试"+id+"_2", true);
ZtreeVo ztreeVo3 = new ZtreeVo(id+"_3", "测试"+id+"_3", true);
ZtreeVo ztreeVo4 = new ZtreeVo(id+"_4", "测试"+id+"_4", true);
l.add(ztreeVo1);
l.add(ztreeVo2);
l.add(ztreeVo3);
l.add(ztreeVo4);
}
System.out.println(JSONArray.fromObject(l).toString());
writeJSON(JSONArray.fromObject(l).toString());
return null;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
protected void writeJSON(String json) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.write(json);
writer.flush();
writer.close();
}
}