ActionForm的生命周期浅探

    看了很多的资料书籍,都提了一下ActionForm的生命周期。例如,在“Programming Jakarta Struts"中是这样描述的:“控制器收到的请求”->“创建或再循环ActionForm”->“调用reset()“->“正确 保存ActionForm”->“由请求组合ActionForm”->“验证ActionForm”。如果验证不通过返回到输入,否则调用 Action的execute()方法。

     我们来看一看RequestProcessor()的process()方法的部分代码。经过一些基本的处理(如Locale,Role等)之后,会调用 processActionForm方法,此方法返回一个ActionForm。然后用processPopulate方法将请求参数传给这个 ActionForm,之后进行验证。


// Process any ActionForm bean related to this request
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}


processActionForm()方法又调用RequestUtils.createActionForm()这个静态方法来创建ActionForm,并把创建的ActionForm保存在合适的作用域,以便下次使用。

RequestUtils.createActionForm()方法并不是一上来就创建ActionForm,而是先查看一下在合适的作用域内有没有存在的ActionForm


if ("request".equals(mapping.getScope())) {
instance = (ActionForm) request.getAttribute(attribute);
} else {
session = request.getSession();
instance = (ActionForm) session.getAttribute(attribute);
}


如果没找到,才会根据struts-config.xml中的actionmapping找到name属性(ActionForm的逻辑名),根据逻辑名 再找到ActionForm的类名,然后会用类似Class.forName("ActionForm's full class name").newInstance()来动态创建这个ActionForm类的实例。当然,它还要考虑DynaActionForm的情况,但原理是 一样的。这么看来,ActionForm的生命周期不算复杂,也没有“探”的必要。在工作中,发现实际情况并不这么简单。

以上为转载内容,下面我自己来写点东东。

在struts-config.xml中,一个简单的配置Action的写法如下:
<action path="/corpInfo"  
             type="com.greatchn.xsglweb.struts.action.CorpInfoAction"
             name="corpInfoForm"
             input=""
             attribute="corpInfoForm"
             scope="request">
        <forward name="corpInfo" path="/corpInfo.jsp" redirect="false"/>
        <forward name="corpInfoList" path="/corpInfoList.jsp" redirect="false"/>
        <forward name="corpInfoLinkInfo_jsp" path="/corpInfoLinkInfo.jsp" redirect="false"/>
</action>

scope属性定义的作用于范围可以通过代码中mapping.getScope()方法取出来,attribute属性的作用是定义ActionForm在作用域范围内的key值,attribute属性是可以起任何名字的,不一定非要和ActionForm名称相同。

如:

attribute="corpInfoForm"
scope="request"

就相当于:request.setAttribute("corpInfoForm",corpInfoForm);

另外,在跳转方式上是可以选择的,如上面的配置当中:redirect="false"代表转发,而redirect="true"则是代表重定向,这点很重要,默认方式是转发。

为了研究ActionForm的生命周期,举个例子:

如下图:

当所有的跳转都是转发方式的,则在b.jsp中可以通过

FormA formA = (FormA)request.getAttribute("formA");得到FormA的示例,当然前提是action的配置中要定义attribute、scope属性,如下:

<action path="/actionA"                            
    type="com.greatchn.xsglweb.struts.action.ActionA"
    name="formA"
    input=""
    attribute="formA"
    scope="request">

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值