1. 程式人生 > >action attribute和name 屬性區別

action attribute和name 屬性區別

在一般情況下,actionForm是被儲存在一定的scope中(request或session,通過action的scope屬性來配置),當我們在配置時,指定name而不指定attribute,那麼指定的name值就作為actionForm儲存在scope中的key值,我們可以在action中通過httpServletRequest.getAttribute("指定的name屬性值")來獲得這個actionForm;   當我們既配置了name又配置了attribute,那麼actionForm儲存在scope中的key值就採用attribute屬性指定的值了,這時要通過httpServletRequest.getAttribute("指定的attribute屬性值")來獲得actionForm,此時通過httpServletRequest.getAttribute("指定的name屬性值")是不能獲得actionForm的。 
  
  所以,是否配置attribute屬性就決定了actionForm儲存在scope中的key值是採用name,還是採用attribute
 2、 在《Programming Jakarta Struts》這本書中的第四章“Configuring the Struts Application”中這樣一段說明來分別闡述這兩
個屬性:(102頁)
++++++++
atribute:
++++++++
The name of the request or session scope attribute under which the form. bean for this action can be accessed.
A value is only allowed here if there is a form. bean specified in the name attribute. This attribute is
optional and has no default value.

++++++++
name:
++++++++
The name of the form. bean, if any, that is associated with this action. This value must be the name attribute
from one of the form-bean elements defined earlier. This attribute is optional and has no default value.

最初看這些真的還是不好區分這兩者。不過在仔細看過struts的原始碼以後,豁然開朗。。。

下面主要對attribute進行解釋,應為沒有人會對name屬性不瞭解的(呵呵。。。)


解釋:在struts例項化actionform的時候,有兩種情況:如果已經存在,那麼從記憶體中取回;如果第一次例項化,那麼建立,並放入記憶體。
這樣就有一個問題了,struts是根據什麼來取回並建立actionform的呢,答案就是attribute的值。讓我們進入struts的原始碼:


public static Actionform. createActionform(
HttpServletRequest request,
ActionMapping mapping,
ModuleConfig moduleConfig,
ActionServlet servlet) {
。。。。
。。。
// Is there a form. bean associated with this mapping?
//得到action mapping中attribute的值
String attribute = mapping.getAttribute();
。。。。
。。。。
Actionform. instance = null;
HttpSession session = null;
//yes!!就在這裡了,把建立以後的actionform放在request或者session裡,看到放入的名字了麼,就是mapping.getAttribute();
if ("request".equals(mapping.getScope())) {
instance = (Actionform) request.getAttribute(attribute);
} else {
session = request.getSession();
instance = (Actionform) session.getAttribute(attribute);
}
。。。
。。。


}


下面又有一個問題浮出水面:如果我沒有在action mapping中指定attribute呢,那struts 是如何解決的?
答案很簡單,如果單從結果上看,此時struts使用的name的值,為什麼呢,看struts原始碼:


protected String attribute = null;

public String getAttribute() {
//yes!!!!就在這裡,看到了吧,如果你沒有設定attribute,那麼struts 會把name的值拿過來用。呵呵。。。
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;