struts2valuestack

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 stack ie., keep pushing whatever attribute it reads?


Solution

  • 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.