How to fetch object properties from selected object in Struts 2

百般思念 提交于 2019-12-30 10:37:29

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!