How does ValueStack in Struts2 work?
Consider the following code .
public class SampleAction {
private String[] sampleArray1 = new String[]{"item1","item2","item3"};
private String[] sampleArray2 = new String[]{"a","b","c"};
private List lst = new ArrayList();
lst.add(1)
lst.add(2)
//Getters and setters
}
Now which of the above attributes will be in value stack when we try to access it in JSP? Does it work like a normal开发者_Python百科 stack ie., keep pushing whatever attribute it reads?
I think you are confusing this: what Struts2 puts in the stack are not the properties, but the objects that hold those properties.
Let say in your jsp you write
<s:property value="xxx" />
Then Struts2 will iterate in your stack to find an object that has the property xxx
, i.e. a class that has a public method getXxx()
. And Struts2 places your current action (an instance of SampleAction
) in the top of the stack. So, it will first search for a SampleAction.getXxx()
method - if not found, it will look further down the stack. (actually you can put other objects in the stack, above the Action -perhaps in the same jps- but let it keep simple).
Then, in your example, all sampleArray1 sampleArray2 lst
(if they have public getters) will be accesible in the jsp. But it's not that sampleArray1
is "in the stack" (even less its elements!), the action is in the stack.
So, for example you could write:
<s:iterator value="sampleArray1">
<p>item is: <s:property/></p>
</s:iterator>
Here, in the first line the sampleArray1
property is found in the action, that is in the stack. The iterator tag puts then each value inside the sampleArray1 in the top of the value stack, and that is grabbed in the second line and printed.
Value Stack
Value stack is used by Struts-2, to store important objects. ActionInstance and member variables are stored in value stack and JSP can access it through value stack.
Note: Value stack behaves as virtual object.
If two member variables have same name, How value stack handles conflicts? Value stack receive a request for member variables then it searches from first to last if the member variable name matches, it sends the value to JSP. For specific member variable to access,we have to access or traverse the object graph.
精彩评论