Search code examples
javajspjakarta-eestruts2ognl

Using a LabelValueBean properly


I have a variable:

private ArrayList<LabelValueBean> circleNameIdList;

inside my Action class where it's value get populated.

I want to display the label in my drop-down in JSP and when one label is selected, the corresponding value to that particular label in circleNameIdList to be passed to the server. Eg.: If label: NewYork is selected then it's corresponding id = 5, is sent to the server.

How can I achieve this?

Up till now I was doing like this in JSP:

<s:select list="#session.circleNameIdList" label="Select Circle:" name="circleNameIdList" id="circleNameIdList"></s:select>

However, it display is not correct.


Solution

  • I see you are using a LableValueBean to populate and show a dropdown. It's a former bean used at last to display a list of objects. In Struts2 you're no longer required such a helper bean. You can display a list of objects by specifying a key field that would hold a unique value of the selected option and a value to be shown as the option text. For example if your object

    public class Circle {
       private Long id;
       //getter and setter here
    
      private String name;
      //getter and setter here
    } 
    

    and you have in the action class

    private List<Circle> circleNameIdList;
    //getter and setter here
    
    /**
     * Hold the selected value
     */
    private Long circleId;
    //getter and setter here
    

    then

    <s:select id="circleNameIdListID" label="Circle:" name="circleId" 
      list="circleNameIdList"   listKey="id" listValue="name" headerKey="-1" headerValue="Select Circle"/>
    

    could be used to show the dropdown.