关于JAVA中struts-config里action元素里的attribute属性

转自:http://hi.baidu.com/%D1%C7%D6%DE%C6%C0%C2%DB/blog/item/0704e246cfdb130c6a63e5fe.html

这是在网上查到的关于attribute的解释.
1)应用前提,attribute只有在设置了name后才有意义。
2)attribute可以实现对象的重用,即如果设置了attribute属性,在创建actionform是,会先去查找相应的scope中是否有此对象,如果有,则重用,否则创建新的对象。
3)当你将创建的acitonForm保存到相应的scope中时,你想用一个更有意义的名字来访问它时,它就有意义了。

可是,看到"一个更有意义的名字的时候", 我好像有点理解了
<action
attribute="newLoginForm"
name="loginForm"
type="loginAction"
scope="request"
path="/login">


在struts实例化actionform的时候,struts是根据attribute的值来查找并创建actionform,有两种情况:如果已经存在,那么从内存中取回;如果第一次实例化,那么创建,并放入内存。

org.apache.struts.util.RequestUtils中的源代码

    public static Actionform createActionform(
HttpServletRequest request,
ActionMapping mapping,
ModuleConfig moduleConfig,
ActionServlet servlet) {
       ............
       ............

        String attribute = mapping.getAttribute();
       ......
        Actionform instance = null;
HttpSession session = null;

        if ("request".equals(mapping.getScope())) {
instance = (Actionform) request.getAttribute(attribute);
} else {
session = request.getSession();
instance = (Actionform) session.getAttribute(attribute);
}
       ................
         ................
      
        }
      
如果没有配置attribute属性的话, struts才会从name属性里读出要创建的formbean 的名字,并创建一下实例,看下边的源代码就知道了, 呵呵.


org.apache.struts.config.ActionConfig

    protected String attribute = null;

public String getAttribute() {
//就是这里了.
        if (this.attribute == null) {
return (this.name);
} else {
return (this.attribute);
}
}

public void setAttribute(String attribute) {
if (configured) {
throw new IllegalStateException("Configuration is frozen");
}
this.attribute = attribute;
}

猜你喜欢

转载自wjc-3306.iteye.com/blog/1139967