`
zengshaotao
  • 浏览: 756725 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JSON中result的root属性

 
阅读更多

 

struts2.1.8以后,加入了json的plugin插件包,使用时仅需把插件包(struts2-json-plugin-2.2.1.1.jar)放入到项目中的WEB-INF/lib下面就可以。这里重点解释返回结果result中的root参数的含义,相对于其他参数,例如includeProperties, excludeProperties,excludeNullProperties等,比较难以理解。
  (1)struts.xml 配置:
  <struts>
  <constant name="struts.i18n.encoding" value="UTF-8" />
  <package name="default" namespace="/" extends="json-default">
  <action name="jsontest" class="com.test.action.JsonJqueryStruts2Action">
  <result name="regInfo" type="json">
  <param name="root">userInfo</param>
  <!-- <param name="includeProperties">userInfo.userId,userInfo.userName</param> -->
  <param name="includeProperties">userId,userName</param>
  <param name="excludeNullProperties">true</param>
  </result>
  </package>
  </struts>
  (2)Action类:类中有一个String类型的属性message,以及一个bean叫UserInfo
  public class JsonJqueryStruts2Action extends ActionSupport {
  private String message; //使用json返回单个值
  private UserInfo userInfo; //使用json返回对象
  ... ...
  (3)表单:form中必须与Action类中的属性名字大小写完全对应,不然会找不到该字段
  <form>
  用户ID:<input name="userInfo.userId" type="text"/><br/>
  用户名:<input name="userInfo.userName" type="text"/><br/>
  ... ...
  (4)json.js文件的ajax方法:
  //向服务器发送表达数据
  $("#regRe").click(function(){
  //把表单的数据进行序列化
  var params = $("form").serialize();
对于中文,注意乱码的处理,前面已经有文章说过了。
  //使用jQuery中的$.ajax({});Ajax方法
  $.ajax({
  url:"jsontest!regUserInfo.action",
  type:"POST",
  data:params,
  dataType:"json",
  success:function(data){
  //清空显示层中的数据
  $("#message").html("");
  //为显示层添加获取到的数据
  //获取对象的数据用data.userInfo.属性
  //$("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
  //.append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
  $("#message").append("<div><font color='greed'>111:"+data.userId+"</font></div>");
  $("#message").append("<div><font color='greed'>222:"+data.userName+"</font></div>");
  if( typeof(data.message)!='undefined' ){
  $("#message").append("<div><font color='greed'>结果:"+data.message+"</font></div>");
  }else{
  $("#message").append("<div><font color='greed'>结果是message没定义!"+data.message+"</font></div>");
  }
  ... ...
  以上是jquery+json+struts2的主要核心配置和代码,请注意struts2配置中指定了result的name="root",所谓root的含义,是指返回的json数据的根为root中指定的bean类,例如此处为userInfo,如果没有指定root属性,则默认使用Action作为返回的json数据的根,区别如下:
  result中使用了root参数后返回的json数据:
  {"userInfo":[
  {"userId":"Patrick", "userName":"123456"}
  ]}
  result中没设置root参数返回Action中的json数据:
  {"data":[
  {"userInfo":[ {"userId":"Patrick", "userName":"123456"} ] },
  {"message":"testMesssageData"}
  ]}
  所以我们要注意,如果设置了root属性之后,<param includeProperties></param>中就应该直接使用userId,userName而非userInfo.userId,userIndo.userName了。
  此外,json.js代码中还展示了遇到类似message等属性返回后是undefined的情况可以使用typeof()!='undefined'进行判断
分享到:
评论

相关推荐

    Json + jsp 实例

    &lt;package name="json" extends="json-default" namespace="/" &gt; &lt;result type="json"&gt; &lt;param name="root"&gt;result &lt;/result&gt; &lt;/struts&gt;

    Python遍历文件夹 处理json文件的方法

    有两种做法:os.walk()、pathlib...analysis_root_dir = D:\\analysis_data\json_file store_result=D:\\analysis_data\\analysis_result\\dependency.csv def parse_dir(root_dir): path = Path(root_dir) all_json_

    jsonapi:Apicase的JSON API插件

    const Root = new ApiService ( fetch , { url : "/api" } ) . use ( jsonApiPlugin ) // &lt;- Add this line 用法 想象一下,我们的API路由具有以下result.body : { " data " : [ { " id

    自动化执行-钉钉机器人通知.pdf

    self.failed = root.getAttribute('failed') self.skipped = root.getAttribute('skipped') #构建的次数统计在json⽂件中 file = open(REPORT_URL_FILE,'r') self.reportUrl=json.load(file)['reportUrl'] #发送报告...

    JSONException:com.alibaba.fastjson.JSONException: expect ‘:’ at 0, actual = 已解决

    检查你代码的 JSONEObject.fromObject(result) 代码位置,参数result不符合Json的定义格式,所以无法转换成Json格式,导致报出上述错误。 解决办法: 好好检查下你的result参数,按照Json规范定义。 如果一定要输出...

    report 开源的访问层中间件,基于java平台

    e)XML_BODY:xml数据请求方式key名称,默认为root f)MONITOR_FILE_PATH:统计数据保存地址 默认为/report/report.cc g)END_INVOKE:请求通道链终端类。 系统默认 &lt;!--如果不是采用report返回体,则必须配置以下几项,...

    python和js交互调用的方法

    $.getJSON($SCRIPT_ROOT + '/_add_numbers',data, function(data) { $('#result').text(data.result); $('input[name=a]').focus().select(); }); 后端pthon代码如下 # ajax,Get方式与js交互(非

    javaee三大框架整合宅急送项目lib包

    &lt;param name="root"&gt;result &lt;/result&gt; 在页面抓取中转信息,回显 $.post("${pageContext.request.cotnextPath}/processinstance_showInfo.action", {"pid": pid}, function(data){ $.messager.alert(...

    rbatis-core:蝙蝠核心

    支持bigdecimal,json解码,async_std,tokio use rbatis_core :: db :: {DBPool}; fn main () -&gt; Result &lt;(), rbatis_core::Error&gt;{ async_std :: task :: block_on ( async move { //Automatic judgment of...

    mininet-n-ryu-routing-algorithm-comparator:一堆描述拓扑创建,拓扑,测试数据,实时图形渲染,表创建和图表创建的脚本和文件

    Mininet + Ryu路由算法比较器 一堆脚本和文件,描述了拓扑创建,拓扑,测试数据,实时图形... 以root身份运行make 。 可以安全删除的文件 rm -rf boxplots rm -rf resultcache rm -rf *.json rm -rf *.pdf rm -rf

    仿天猫商城

    /** * ECSHOP 首页文件 * ====================... die($json-&gt;encode($result)); } /*------------------------------------------------------ */ //-- 判断是否存在缓存,如果存在则调用缓存,反之读取相应内容

    x-ray-request:请求 X 光驱动程序

    select ( [ { $root : '.result' , title : '.title' , link : 'a[href]' } ] ) . write ( 'out.json' ) ;应用程序接口xray#request(url, fn) 使用 Request 发出请求车身处理器此驱动程序接受可选的主体处理器。 第...

    Node.js流程控制引擎Stepify.zip

     root.done(err, JSON.parse(body).code);  });  }, [appId], [redirectUri])  .step('getToken', function(code) {  var root = this;  request.post('[token_uri]', function(err, res, body) {...

    PHP微信支付WxPayPubHelper

    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $array_data; } /** * 作用:以post方式提交xml到对应的接口url */ public ...

    jquery1.11.0手册

    $.getJSON(url,[data],[fn]) $.getScript(url,[callback]) $.post(url,[data],[fn],[type]) ajax 事件 ajaxComplete(callback) ajaxError(callback) ajaxSend(callback) ajaxStart(callback) ajaxStop...

    ORM软件monalisa-orm.zip

    @DB(url="jdbc:mysql://127.0.0.1:3306/test" ,username="root", password="root") 一些基本的数据库操作: //insert new User().setName("zzg.zhou").setStatus(1).save(); //parse data from type: Map, ...

    asp.net mvc

    The FileResult action result now supports non-US-ASCII characters in file names. Methods and properties of the TempDataDictionary class have been improved to better handle the case when items are ...

Global site tag (gtag.js) - Google Analytics