关于Struts2中在多个action中传递fieldError的问题

今天写项目时遇到了这样的问题:

要实现一个修改个人信息的问题,第一次点击连接时执行的是查询的action,当把要修改的内容写好后,点击修改按钮提交表单。如果填写的数据规范没问 题,如果不规范,就不会通过validate,进而跳转到input页面,返回查询页面让用户重新输入。结果出现问题,在网上找了大半天。没有结果,不过 还好找到了提同样问题的童鞋~~他是这样描述的:

“有个问题是这样的
A.jsp(点击一个超链接)-->
A.action(在后台取数据, 比如取了一个list放在ActionContext]里, 然后dispatcher到B.jsp)-->
B.jsp(把list显示出来, 同时在表单输入别的数据, 提交)-->
B.action(对B.jsp里的数据进行效验, 如果错误...)

现在问题就来啦, 当在B.action里效验错误的时候, 我应该怎么返回输入页面让用户重新输入呢,
如果dispatcher到一个B.jsp, 那从后台取出的list就没有了,
如果redirectAction到A.action重新取数据, 那错误提示信息fieldError就不见了
两难啊!!! 大家是怎么解决这个问题的?”

  public  String execute()  throws  Exception {

    ActionContext ctx  =  ActionContext.getContext();

    ctx.put( "listTemp" ,  new  ArrayList());

     return  SUCCESS;

  }

后来我仔细分析了一下,后台的list之所以没有数据时因为,程序没有执行到execute方法,因为在validate方法那就已经没通过,所以直接跳转到input页面了。

 

再仔细查找了相关资料 发现apache的文档 http://struts.apache.org/2.x/docs/how-do-we-repopulate-controls-when-validation-fails.html中写道
When validation fails, we typically forward back to the same server page, so that the errors can be presented, and so that the client can fix the problem and resubmit the form. Of course, aside from the errors, we may also need to present rich controls, like drop down lists.
If we try to populate rich controls in an Action method, like input or execute , and validation fails, the method will not be invoked, and the controls are not populated. Two alternative ways to populate controls are the Preparable interface and the action tag.
大致的意思是但出现validation错误的时候会影响到Action的正常执行,这个时候应该实现Preparable 接口中的prepare()方法,这个方法中的操作不会因为validation错误而不执行。
联想到上面的错,会不会也是因为addActionError而导致不能正常使用action标签了。为此在input的Action中实现Preparable接口并在prepare()方法中put listTemp。修改代码如下

public   class  Sxt_DaoHang_XianShiAction  extends  ActionSupport   implements  Preparable{



  @Override

   public  String execute()  throws  Exception {

     return  SUCCESS;

  }



   public   void  prepare()  throws  Exception {

    ActionContext ctx  =  ActionContext.getContext();

    ctx.put( " listTemp " , new  ArrayList());

  }

}

执行---成功

原来prepare是在validate拦截器之前执行的。因此可以把一些初始化的工作放到prepare方法中去执行

 

http://blog.sina.com.cn/s/blog_4b6f8d150100i9wm.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值