有以下的一个form类,它有3个属性,2个是javaBean,还有一个是javaBean的数组
- public class PrmMainType extends ActionForm{
- private PlyCalVhlType plyCalVhlType;
- private PlyRdrType[] plyRdrType;
- private PlyFrcVhlType plyFrcVhlType;
- public PlyCalVhlType getPlyCalVhlType() {
- return plyCalVhlType;
- }
- public void setPlyCalVhlType(PlyCalVhlType plyCalVhlType) {
- this.plyCalVhlType = plyCalVhlType;
- }
- public PlyRdrType[] getPlyRdrType() {
- return plyRdrType;
- }
- public void setPlyRdrType(PlyRdrType[] plyRdrType) {
- this.plyRdrType = plyRdrType;
- }
- public PlyFrcVhlType getPlyFrcVhlType() {
- return plyFrcVhlType;
- }
- public void setPlyFrcVhlType(PlyFrcVhlType plyFrcVhlType) {
- this.plyFrcVhlType = plyFrcVhlType;
- }
- }
现在有一个需求就是要把页面的值注入到form中去,在开发的过程中遇到了很多意想不到的事:
首先没有使用过复杂对象数组注值,原来都是使用String数组,只要在页面使用相同的名字在后台就会获得String数组。而对于上面的这种情况则需要使用plyRdrType[0].SNclmDesc这种形式了
- <input type="checkbox" name="plyRdrType[0].SNclmDesc" value="Y">
这个地方碰到了2个问题plyRdrType对象的类型原本不是这样定义的是非规范定义:
- private _plyRdrType[] plyRdrType;
这在Struts中好像是不允许的:你必需按照骆驼峰的方式进行规范命名,否则你将自食其果。
不知道你们注意到上面的input中SNclmDesc的第一个字母是大写的没,其实在vo中是sNclmDesc。用小写的时候你会发现下面的异常(用nested标签的时候)或者你会发现其它的都取到值了而这个属性没有:
- PrmMainType has no property defined by "plyRdrType[0].sNclmDesc"
如果你还有以d打头命名的属性时也会遇到上面的问题,改成大写的就可以了。
以上的是页面方面遇到的问题,这个时候提交的话是不会出现你所期望的结果的,它会无情的给你抛出一个nullpoint exception,
为什么?没有进行初始化。为什么?我也不清楚。。。。
只要在PrmMainType中加入下面的代码就可以了:
- public void reset(ActionMapping mapping, HttpServletRequest request) {
- String plyRdrTypeLs=request.getParameter("plyRdrTypeLength");
- int plyRdrTypeLength=(new Integer(plyRdrTypeLs)).intValue();
- plyRdrType=new PlyRdrType[plyRdrTypeLength];
- plyCalVhlType=new PlyCalVhlType();
- for(int i=0;i<plyRdrTypeLength;i++){
- plyRdrType[i]=new PlyRdrType();
- }
- plyFrcVhlType=new PlyFrcVhlType();
- }
plyRdrTypeLength是页面中的一个hidden属性,用来定义plyRdrType的长度,由js来控制。
贴一段页面代码
- <form name="prmMainType" method="post" action="<%=request.getContextPath() %>/formArrayAction.do?cmd=getData">
- <input type="hidden" name="plyRdrType[0].FRdrAmt" value="50000">
- <input type="hidden" name="plyRdrType[0].FRdrAmtDes" value="50000">
- <input type="submit" value="提交">
- <input type="hidden" name="plyRdrTypeLength" value="2">
- </form>
这样基本上就可以了,下面介绍下nested标签。这是一个并不常用的标签,它的一个优点就是可以在页面展示很好的业务逻辑,它允许你按照form中的那种层级关系在页面中进行布局:
- <html:form action="/formArrayAction.do?cmd=getData">
- <nested:nest property="plyRdrType[0]">
- <nested:checkbox property="SNclmDesc" value="Y"></nested:checkbox>
- <nested:hidden property="SNclmDescDes" value="Y"></nested:hidden>
- </nested:nest>
- <html:submit>提交</html:submit>
- </html:form>
nested标签也可以完成上面的功能,不过有些地方有点麻烦,大家自己去体会吧。
最后说一句,Struts之类的框架是为了给大家提供方便的,不能为了使用而使用,当你觉得使用它增加了复杂度的时候可以考虑下其他的方式。