json数据传输

来源:互联网 发布:女程序员的职业规划 编辑:程序博客网 时间:2024/05/18 00:21

Java代码:
package com.jia;

public class UserAction {
 protected transient HttpServletResponse response;

 public String queryList(List<OppUser> list)
 {
  this.sendJson(list);
 }

/**
  * 将json数据发送到前台页面
  */
 public static void sendJson(Object object) {
  JSONArray jsonObject = JSONArray.fromObject(object);
 
  System.out.println("发送到前台的json数据为:\n" + jsonObject.toString());
 
  HttpServletResponse response = MyContext.getServletResponse();
  String fullContentType = "application/json;charset=UTF-8";
  response.setContentType(fullContentType);
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);

  PrintWriter pw = null;
  try {
   pw = response.getWriter();
   pw.print(jsonObject);
  } catch (IOException E) {
  } finally {
   if (pw != null) {
    pw.flush();
    pw.close();
    try {
     response.flushBuffer();
    } catch (IOException e) {
    }
   }
  }
 }
}

package crm.common;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;

public class MyContext
{
 private transient static ActionContext context;
 private transient static Map<String,Object> mapRequest;
 private transient static Map<String,Object> mapSession;
 private transient static HttpServletRequest servlrtRequest;
 private transient static HttpServletResponse servletResponse;
 private transient static HttpSession servlrtSession;
 
 @SuppressWarnings("unchecked")
 public static Map<String, Object> getMapRequest() {
  context=ActionContext.getContext();
  mapRequest=(Map<String,Object>) context.get("request");
  return mapRequest;
 }
 public static Map<String, Object> getMapSession() {
  context=ActionContext.getContext();
  mapSession = (Map<String,Object>)context.getSession();
  return mapSession;
 }
 public static HttpServletRequest getServlrtRequest() {
  servlrtRequest=ServletActionContext.getRequest();
  return servlrtRequest;
 }
 public static HttpServletResponse getServletResponse() {
  servletResponse = ServletActionContext.getResponse();
  return servletResponse;
 }
 public static HttpSession getServlrtSession() {
  servlrtRequest=ServletActionContext.getRequest();
  ServletActionContext.getResponse();
  servlrtSession = servlrtRequest.getSession();
  return servlrtSession;
 }
}


struts.xml:
<action name="queryList" class="userAction" method="queryList">
  <result name="json"/>
 </action>

js:
function queryList() {
  $.ajax({
   url : "queryList.action",
   data : {
   _:new Date().getTime()
   },
   type : "post",
   dataType : "json",
   success : function(data) {
    openEditWindow(data[0]);
   },
   error : function(data) {
    showMessage(data.responseText);
   }
  });
 }