Struts2 validation验证失败之后s:select的list返回不了的解决

来源:互联网 发布:c语言 libevent 编辑:程序博客网 时间:2024/04/30 02:18

Struts2 validation验证失败之后s:select的list返回不了的解决

查找了一番说是调用静态方法或者静态变量解决,然后在SO中找到其他的解决方法.

Pretty much everyone starting with Struts2 encounter this problem, soon or later.

When requesting an Action in Struts2, your request will pass through an Interceptor Stack (a list of Interceptors); every Interceptor does is particular business, then redirect the request (in case of errors) or proceed the execution to the next Interceptor, or to the Action if it is the last.

The validation is performed by the Validation Interceptor. If the validation fails, it will hijack the request and will redirect it to the input result defined in struts.xml. No matter if the validation is by XML, by Annotation or in a validate() method inside the Action: the Action is not reached ! Then, everything inside the execute() method, or the method you are calling (if you are using a custom one) is not executed;

If the loading of your List elements is demanded to the execute() method, it won’t be performed in case of an input result.

The main ways to avoid this problem are:

  1. Implement Preparable Interface, and put all the data loading stuff into the prepare() method.
    That method is run by the Prepare Interceptor, that is placed BEFORE the Validation Interceptor;
    it will always run, and it will run before the validation, no matter which method of your action (execute() or something else) you are calling, nor if you are encountering validation errors;
  2. Use tag from the JSP, to call dummy Actions returning JSP snippets;
  3. Use a redirectAction as the input result type, to the execute() (or something else) method, as you are doing.
    While redirecting, it will lose all the request parameters (including action errors, field errors, action messages etc) , then you will need to manually copy them by declaring them in the struts.xml as parameters of the redirectAction result.
    The first way is the preferred, imho.

just found it in the official documentation too: how do we repopulate controls when validation fails ?

译:
每个用struts2的人,都会迟早碰到这个问题。
当请求一个Struts2的action时,你的请求将会通过拦截器栈拦截;每个拦截器是一个特殊的业务,然后将请求转发或者继续执行下个拦截器,或者如果没有下一个拦截器的话,就执行action。

验证是使用验证拦截器执行的。如果验证失败,它将劫持请求然后转到input页面。不论验证是写在xml中,还是使用Annotation,还是action中的validate()方法中,Action都不会执行!然后,execute()方法或者你调用的方法都不会执行。

如果你的list依赖于execute()或者调用的方法,那么在input的情况下它将获取不到。

主要避免这种问题的方法有:
1. 实现preparable接口,并且把所有data加载的东西放在prepare()方法中。这个方法是preparable接口提供的,并且在validate之前调用的,所以不论验证的结果是什么,它都会执行。
2. 使用 标签,调用空action返回JSP部分内容.
3. 使用转发action作为input的类型的结果,执行其他的方法来返回数据。在转发时,默认将会失去转发的参数(包括action errors,field errors, action message等).你需要手动拷贝生命在struts2的配置文件中声明这些参数。

第一中方法是比较推荐的.

也发现官方文档有这么说:当验证失败时怎么重新取得控制?

0 0