Struts1.X 源码分析之ActionForm赋值原理

struts1在处理请求参数之前,首先会根据配置文件action节点的name属性创建对应的ActionForm。如果配置了name属性,却找不到对应的ActionForm类也不会报错,只是不会处理本次请求的请求参数。

如果找到了对应的ActionForm类,则先判断是否已经存在ActionForm的实例,如果不存在则创建实例,并将其存放在对应的作用域中。作用域由配置文件action节点的scope属性来指定,其值可以为request或session(存储在作用域中的属性名由action节点配置的attribute属性指定,如果没有该属性,则由name属性指定)。其部分源代码如下:

 //ClassName:org.apache.struts.action.RequestProcessor

 protected ActionForm processActionForm(HttpServletRequest request,
        HttpServletResponse response, ActionMapping mapping) {
        // Create (if necessary) a form bean to use
        ActionForm instance =
            RequestUtils.createActionForm(request, mapping, moduleConfig, servlet);

        if (instance == null) {
            return (null);
        }

        // Store the new instance in the appropriate scope
        if (log.isDebugEnabled()) {
            log.debug(" Storing ActionForm bean instance in scope '"
                + mapping.getScope() + "' under attribute key '"
                + mapping.getAttribute() + "'");
        }

        if ("request".equals(mapping.getScope())) {
            request.setAttribute(mapping.getAttribute(), instance);
        } else {
            HttpSession session = request.getSession();

            session.setAttribute(mapping.getAttribute(), instance);
        }

        return (instance);
    }

接着,struts1开始处理request请求参数,并将其放置在一个HashMap中,最后调用
//bean为ActionForm实例
//properties为存放请求参数的HashMap
BeanUtils.populate(bean, properties);

将请求参数中对应参数的值赋给ActionForm中对应的属性名,并且支持嵌套属性赋值。例如名为user.name的参数值,BeanUtils将会赋值给ActionForm中属性名为user的对象的name属性。

猜你喜欢

转载自chenbowen00.iteye.com/blog/2211747
今日推荐