Search code examples
jspstruts2ognlstruts-tags

Submit <s:radio> tag selection with different attribute from the one being displayed


For the sake of simplicity, I will define the scenario as: class Person defines an object with an id (int) and a name (String) attribute. I created a List<Person> persons, which are loaded into the JSP page by its respective Action class method (getPersons()), to populate an <s:radio> tag. So far, so good, the JSP populates the <s:radio> accordingly. I can select and submit an option to the action class (defined in the JSP's <form> element). My problem is that I can only submit the name of the selected Person in the <s:radio>, when what I really want is to submit the Person's id. How can I do it?

Practical example: I have 2 Persons on the <s:radio> list, John (with ID=1), and Peter (with ID=2). I want to display their names on the <s:radio> element, but if I choose Peter, I want to submit 2 to the action class, instead of its name.

Code below:

JSP

<form action="submitData" class="ink-form all-100 small-100 tiny-100" method="post">
    <s:radio label="persons" name="personId" list="persons.{name}" />
</form>

Action class (submitData action)

public class SubmitData extends ActionSupport
{
    private String personId;

    public String execute()
    {
        System.out.println("Person ID: "+personId);

        return SUCCESS;
    }

    public void setPersonId(String PersonId)
    {
        this.personId = personId;
    }
}

Solution

  • In OGNL this persons.{name} is called projection and you don't really need it in <s:radio> tag. Use listKey and listValue attributes to define which property of the objects inside list will be shown and which submitted.

    <s:radio label="persons" name="personId" list="persons" listKey="id" listValue="name" />
    

    One more thing. Person id is an int and you are trying to submit it to personId which is a String. Of course it will work but consider changing personId to int. In that way, later when you want to retrieve Person object from the database you don't need to convert String back to int.