从前台到后台的数组或集合为null问题

来源:互联网 发布:雪人企业版是什么软件 编辑:程序博客网 时间:2024/05/22 01:36

<iframe id="cproIframe1" src="http://pos.baidu.com/acom?adn=1&amp;at=99&amp;aurl=&amp;cad=1&amp;ccd=32&amp;cec=UTF-8&amp;cfv=0&amp;ch=0&amp;col=zh-CN&amp;conOP=0&amp;cpa=1&amp;dai=1&amp;dis=0&amp;ltr=http%3A%2F%2Fm.ddvip.com%2Ftech%2F1000136684.html&amp;ltu=http%3A%2F%2Fm.ddvip.com%2Ftech%2F1000136684.html&amp;lunum=6&amp;n=23010034_cpr&amp;pcs=360x570&amp;pis=10000x10000&amp;ps=138x0&amp;psr=720x1280&amp;pss=360x138&amp;qn=37e3d52b4bd9f54a&amp;rad=&amp;rsi0=360&amp;rsi1=54&amp;rsi5=4&amp;rss0=&amp;rss1=&amp;rss2=&amp;rss3=&amp;rss4=&amp;rss5=&amp;rss6=&amp;rss7=&amp;scale=20.3&amp;skin=mobile_skin_white_blue&amp;td_id=2184327&amp;tn=template_inlay_all_mobile&amp;tpr=1438407025886&amp;ts=1&amp;xuanting=0&amp;tt=1438407025844.48.90.109&amp;dtm=BAIDU_DUP2_SETJSONADSLOT&amp;dc=2&amp;di=u2184327&amp;ti=struts%202%20%E4%B8%AD%20%E5%85%B3%E4%BA%8E%E5%AF%B9%E8%B1%A1%E6%95%B0%E7%BB%84%E7%9A%84%E4%BC%A0%E5%80%BC%20--%E8%B1%86%E8%B1%86%E7%BD%91&amp;wt=1&amp;distp=1001&amp;conW=360&amp;conH=54" width="360" height="54" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="text-align: left; font-size: 0px;"></iframe>家用struts2时想必会经常遇到在JS或者JSP中往后台传递对象数组的问题,你是不是在一直为后台取值是null的问题而苦恼呢?下边我来告诉大家究竟如何做才能取到值。

       一、在Action中声明数组对象(这里也可以是List等集合),代码如下:

   public List<User> users = new ArrayList<User>();  


这里有两点需要注意:

1、声明可以是public也可以是private,private 要求必须生成get、set方法,推荐使用第二种方式,原理不再详细说明,有问题可以留言。

2、对象数组(或者集合)必须进行初始化,否则写的再好后台获取的值仍为null。这种情况很多人都容易忽略。(简单提醒下:平时用单个对象时可以从前台到后台传递该对象,但把该对象换成数组对象就不行了,原因在于单个对象有该对象的构造方法可以产生该对象的实例,而数组没有,所以需要数组对象直接new 一个实例出来)。

       二、在页面中或者JS中用get或者post方式进行传值吧,代码如:

<input name="users[0].id" value="1">  <input name="users[0].name" value="张三">  <input name="users[1].id" value="2">  <input name="users[1].name" value="李四">

在Debug模式下加断掉,看看users是不是有值了?

0 0