How to fetch object properties from selected objec

2019-02-19 01:05发布

I have a list of City objects with name and id fields. I use Struts2 and I a have jsp page with a select tag.

<s:select label="Source city" 
          list="cities" 
          name="source"/>

Here is Action class

public class CalculationAction extends ActionSupport {

    private List<City> cities;
    private DataAccessPerformer dao = new DataAccessPerformer();
    private String source;
    private int sourceId;

    public CalculationAction() {
        cities = new ArrayList<City>();
        // getting cities from database
        setCities(dao.getAllCities());
    }

    // getters and setters
}

City class

public class City {

    private int id;
    private String name;

    @Override
    public String toString() {
        return getCityName();
    }

    // getters and setters
}

In this way I'm getting source field initialized, but I can't fetch sourceId.

I tried to change source field type to City, but I got FieldError

Invalid field value for field "source".

How should I properly fetch the id?

1条回答
女痞
2楼-- · 2019-02-19 01:07

To set id to the value of the select tag you should use additional attributes

<s:select label="Source city" 
          list="cities" 
          listKey="id"
          listValue="name"
          name="sourceId"/>
查看更多
登录 后发表回答