action的result节点下的param的name

本文详细解析了Struts2框架中的JSONResult类,介绍了如何通过配置参数实现JSON数据的生成与输出,包括数据格式化、压缩、回调函数支持等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<result name="aaa" type="json">
  <param name="bbb">ccc</param>
</result>

aaa:是action里对应返回的result的名字这个大家都知道。

bbb:这个是最关键的,一般大家看到网上的基本就写成root。

这个param的name是JSONResult类中对应的属性名,不能乱取名字,不然json的创建就会出错。不同的name对应着JSONResult类中不同的属性,JSONResult根据name选择的不同的属性以及name对应的值对返回的json数据进行封装。

ccc:这个就是param的name对应的取值。一般是Action中的变量名。

主要关注jar包是:struts2-json-plugin-x.x.x.jar。

以及它下面的一个类 JSONResult类。

package org.apache.struts2.json;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.WildcardUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.json.smd.SMD;
import org.apache.struts2.json.smd.SMDGenerator;

public class JSONResult
  implements Result
{
  private static final long serialVersionUID = 8624350183189931165L;
  private static final Logger LOG = LogManager.getLogger(JSONResult.class);
  public static final String DEFAULT_PARAM = null;
  private String encoding;
  private String defaultEncoding = "UTF-8";
  private List<Pattern> includeProperties;
  private List<Pattern> excludeProperties;
  private String root;
  private boolean wrapWithComments;
  private boolean prefix;
  private boolean enableSMD = false;
  private boolean enableGZIP = false;
  private boolean ignoreHierarchy = true;
  private boolean ignoreInterfaces = true;
  private boolean enumAsBean = false;
  private boolean noCache = false;
  private boolean cacheBeanInfo = true;
  private boolean excludeNullProperties = false;
  private String defaultDateFormat = null;
  private int statusCode;
  private int errorCode;
  private String callbackParameter;
  private String contentType;
  private String wrapPrefix;
  private String wrapSuffix;
  private boolean devMode = false;
  
  @Inject("struts.i18n.encoding")
  public void setDefaultEncoding(String val)
  {
    this.defaultEncoding = val;
  }
  
  @Inject("struts.devMode")
  public void setDevMode(String val)
  {
    this.devMode = BooleanUtils.toBoolean(val);
  }
  
  public List<Pattern> getExcludePropertiesList()
  {
    return this.excludeProperties;
  }
  
  public void setExcludeProperties(String commaDelim)
  {
    Set<String> excludePatterns = JSONUtil.asSet(commaDelim);
    if (excludePatterns != null)
    {
      this.excludeProperties = new ArrayList(excludePatterns.size());
      for (String pattern : excludePatterns) {
        this.excludeProperties.add(Pattern.compile(pattern));
      }
    }
  }
  
  public void setExcludeWildcards(String commaDelim)
  {
    Set<String> excludePatterns = JSONUtil.asSet(commaDelim);
    if (excludePatterns != null)
    {
      this.excludeProperties = new ArrayList(excludePatterns.size());
      for (String pattern : excludePatterns) {
        this.excludeProperties.add(WildcardUtil.compileWildcardPattern(pattern));
      }
    }
  }
  
  public List<Pattern> getIncludePropertiesList()
  {
    return this.includeProperties;
  }
  
  public void setIncludeProperties(String commaDelim)
  {
    this.includeProperties = JSONUtil.processIncludePatterns(JSONUtil.asSet(commaDelim), "regexp");
  }
  
  public void setIncludeWildcards(String commaDelim)
  {
    this.includeProperties = JSONUtil.processIncludePatterns(JSONUtil.asSet(commaDelim), "wildcard");
  }
  
  public void execute(ActionInvocation invocation)
    throws Exception
  {
    ActionContext actionContext = invocation.getInvocationContext();
    HttpServletRequest request = (HttpServletRequest)actionContext.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
    HttpServletResponse response = (HttpServletResponse)actionContext.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
    

    this.cacheBeanInfo = (!this.devMode);
    try
    {
      Object rootObject = readRootObject(invocation);
      writeToResponse(response, createJSONString(request, rootObject), enableGzip(request));
    }
    catch (IOException exception)
    {
      LOG.error(exception.getMessage(), exception);
      throw exception;
    }
  }
  
  protected Object readRootObject(ActionInvocation invocation)
  {
    if (this.enableSMD) {
      return buildSMDObject(invocation);
    }
    return findRootObject(invocation);
  }
  
  protected Object findRootObject(ActionInvocation invocation)
  {
    Object rootObject;
    Object rootObject;
    if (this.root != null)
    {
      ValueStack stack = invocation.getStack();
      rootObject = stack.findValue(this.root);
    }
    else
    {
      rootObject = invocation.getStack().peek();
    }
    return rootObject;
  }
  
  protected String createJSONString(HttpServletRequest request, Object rootObject)
    throws JSONException
  {
    String json = JSONUtil.serialize(rootObject, this.excludeProperties, this.includeProperties, this.ignoreHierarchy, this.enumAsBean, this.excludeNullProperties, this.defaultDateFormat, this.cacheBeanInfo);
    
    json = addCallbackIfApplicable(request, json);
    return json;
  }
  
  protected boolean enableGzip(HttpServletRequest request)
  {
    return (this.enableGZIP) && (JSONUtil.isGzipInRequest(request));
  }
  
  protected void writeToResponse(HttpServletResponse response, String json, boolean gzip)
    throws IOException
  {
    JSONUtil.writeJSONToResponse(new SerializationParams(response, getEncoding(), isWrapWithComments(), json, false, gzip, this.noCache, this.statusCode, this.errorCode, this.prefix, this.contentType, this.wrapPrefix, this.wrapSuffix));
  }
  
  protected SMD buildSMDObject(ActionInvocation invocation)
  {
    return new SMDGenerator(findRootObject(invocation), this.excludeProperties, this.ignoreInterfaces).generate(invocation);
  }
  
  protected String getEncoding()
  {
    String encoding = this.encoding;
    if (encoding == null) {
      encoding = this.defaultEncoding;
    }
    if (encoding == null) {
      encoding = System.getProperty("file.encoding");
    }
    if (encoding == null) {
      encoding = "UTF-8";
    }
    return encoding;
  }
  
  protected String addCallbackIfApplicable(HttpServletRequest request, String json)
  {
    if ((this.callbackParameter != null) && (this.callbackParameter.length() > 0))
    {
      String callbackName = request.getParameter(this.callbackParameter);
      if (StringUtils.isNotEmpty(callbackName)) {
        json = callbackName + "(" + json + ")";
      }
    }
    return json;
  }
  
  public String getRoot()
  {
    return this.root;
  }
  
  public void setRoot(String root)
  {
    this.root = root;
  }
  
  public boolean isWrapWithComments()
  {
    return this.wrapWithComments;
  }
  
  public void setWrapWithComments(boolean wrapWithComments)
  {
    this.wrapWithComments = wrapWithComments;
  }
  
  public boolean isEnableSMD()
  {
    return this.enableSMD;
  }
  
  public void setEnableSMD(boolean enableSMD)
  {
    this.enableSMD = enableSMD;
  }
  
  public void setIgnoreHierarchy(boolean ignoreHierarchy)
  {
    this.ignoreHierarchy = ignoreHierarchy;
  }
  
  public void setIgnoreInterfaces(boolean ignoreInterfaces)
  {
    this.ignoreInterfaces = ignoreInterfaces;
  }
  
  public void setEnumAsBean(boolean enumAsBean)
  {
    this.enumAsBean = enumAsBean;
  }
  
  public boolean isEnumAsBean()
  {
    return this.enumAsBean;
  }
  
  public boolean isEnableGZIP()
  {
    return this.enableGZIP;
  }
  
  public void setEnableGZIP(boolean enableGZIP)
  {
    this.enableGZIP = enableGZIP;
  }
  
  public boolean isNoCache()
  {
    return this.noCache;
  }
  
  public void setNoCache(boolean noCache)
  {
    this.noCache = noCache;
  }
  
  public boolean isIgnoreHierarchy()
  {
    return this.ignoreHierarchy;
  }
  
  public boolean isExcludeNullProperties()
  {
    return this.excludeNullProperties;
  }
  
  public void setExcludeNullProperties(boolean excludeNullProperties)
  {
    this.excludeNullProperties = excludeNullProperties;
  }
  
  public void setStatusCode(int statusCode)
  {
    this.statusCode = statusCode;
  }
  
  public void setErrorCode(int errorCode)
  {
    this.errorCode = errorCode;
  }
  
  public void setCallbackParameter(String callbackParameter)
  {
    this.callbackParameter = callbackParameter;
  }
  
  public String getCallbackParameter()
  {
    return this.callbackParameter;
  }
  
  public void setPrefix(boolean prefix)
  {
    this.prefix = prefix;
  }
  
  public void setContentType(String contentType)
  {
    this.contentType = contentType;
  }
  
  public String getWrapPrefix()
  {
    return this.wrapPrefix;
  }
  
  public void setWrapPrefix(String wrapPrefix)
  {
    this.wrapPrefix = wrapPrefix;
  }
  
  public String getWrapSuffix()
  {
    return this.wrapSuffix;
  }
  
  public void setWrapSuffix(String wrapSuffix)
  {
    this.wrapSuffix = wrapSuffix;
  }
  
  public void setEncoding(String encoding)
  {
    this.encoding = encoding;
  }
  
  public String getDefaultDateFormat()
  {
    return this.defaultDateFormat;
  }
  
  @Inject(required=false, value="struts.json.dateformat")
  public void setDefaultDateFormat(String defaultDateFormat)
  {
    this.defaultDateFormat = defaultDateFormat;
  }
}

 

转载于:https://www.cnblogs.com/horsen/p/7212497.html

// <summary> /// 获取人员权限 /// </summary> /// <param name=“context”></param> /// <param name=“done”></param> /// <returns></returns> public string getQ(string userid) { var sqlstr = “SELECT lineid, usernum, typeid, user_nickname, typename FROM tb_web_user_articletypes WHERE(usernum = '”+userid+"') "; DataSet ds4 = dbutility.DbHelperSQL.Query(sqlstr.ToString()); return ld.core.dbutility.json.dataTable2Json(ds4.Tables[0]); } /// <summary> /// 获取部门权限 /// </summary> /// <param name=“context”></param> /// <param name=“done”></param> /// <returns></returns> public string QxName(int id) { var qxname = id == 1 ? “生产部管理员” : id == 2 ? “设备检修部管理员” : id == 3 ? “安监部管理员” : “安监部管理员”; var sql = “select lineid from tb_web_article_types where qxname ='” + qxname + “'”; var ds = dbutility.DbHelperSQL.Query(sql.ToString()); var lineid = ds.Tables[0].Rows[0][0].ToString(); var sqlstr = “SELECT * FROM tb_web_article_types WHERE(lineid = " + lineid + " or pid =” + lineid + “) or pid in (” + " select lineid from tb_web_article_types where pid = " + lineid + “)”; DataSet ds4 = dbutility.DbHelperSQL.Query(sqlstr.ToString()); return ld.core.dbutility.json.dataTable2Json(ds4.Tables[0]); } /// <summary> /// 获取部门权限 /// </summary> /// <param name=“context”></param> /// <param name=“done”></param> /// <returns></returns> public string QxNamelist(int id) { var qxname = id == 1 ? “生产部管理员” : id == 2 ? “设备检修部管理员” : id == 3 ? “安监部管理员” : “安监部管理员”; var sql = “select lineid from tb_web_article_types where qxname ='” + qxname + “'”; var ds = dbutility.DbHelperSQL.Query(sql.ToString()); var lineid = ds.Tables[0].Rows[0][0].ToString(); var sqlstr = “select * from tb_web_user_articletypes where typeid in (SELECT lineid FROM tb_web_article_types WHERE(lineid = " + lineid + " or pid =” + lineid + “) or pid in (” + " select lineid from tb_web_article_types where pid = " + lineid + “)) order by lineid desc”; DataSet ds4 = dbutility.DbHelperSQL.Query(sqlstr.ToString()); return ld.core.dbutility.json.dataTable2Json(ds4.Tables[0]); } public override string Process(HttpContext context, ref bool done) { string result = “{"r":"ERROR","msg":"请登录后进行这个操作!"}”; string mode = context.Request[“action”]; string keyvalue = context.Request[“id”]; model.user loginuser = (model.user)context.Session[“ldwebloginuser”]; //loginuser = loginuser == null ? (model.user)context.Session[“ldwebloginuser”] : loginuser; mode = (mode == null) || (mode == “”) ? “QRY” : mode; switch (mode.ToUpper()) { case "QRY": { if (keyvalue == null) { result = GetList(context); done = true; } else result = QxNamelist(Convert.ToInt32(keyvalue)); done = true; break; } case "COMBO": { if (keyvalue == null) { result = getListFilterLimits(); done = true; } break; } } if (loginuser != null) { switch (mode.ToUpper()) { case "MYCHKLIST": { result = getCurrUserCheckList(context); done = true; } break; case "GETQ": { result = getQ(keyvalue); done = true; } break; case "NAMES": { result = QxName(Convert.ToInt32(keyvalue)); done = true; } break; } } return result; } 翻译
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值