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?
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"/>
来源:https://stackoverflow.com/questions/31936598/how-to-fetch-object-properties-from-selected-object-in-struts-2