SpringMVC 3转换<form:checkboxes .. =“”>将String []返回到实体对象</form:checkboxes>

时间:2011-08-08 12:16:08

标签: java spring-mvc annotations spring-3

我有一个与CampaignCities城市有OneToOne关系的实体广告系列。 反过来,CampaignCities包含一组城市;

广告系列实体

    @Entity 
    @javax.persistence.Table(uniqueConstraints={@UniqueConstraint(columnNames={"name","company_id"}), @UniqueConstraint(columnNames={"id"})})
    public class Campaign implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        private Long id;

        @NotEmpty
        @Size(min=1, max=100)
        private String name;

        private Date startDate;

        private Date endDate;

        @Valid
        private Deal deal;

        @Valid
        private Company company;

        @OneToOne
        private CampaignCities cities = new CampaignCities();

CampaignCities实体

@Entity
public class CampaignCities {
    private long id;
    private Set<City> cities = new HashSet<City>();

    @Id
    @javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @OneToMany
    public Set<City> getCities() {
        return cities;
    }

    public void setCities(Set<City> cities) {
        this.cities = cities;
    }
}

城市实体:

@Entity
public class City implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private Long id;

    @javax.persistence.Id
    @javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

我的NewCampaignController

@SessionAttributes(value={"campaign", "campaignCities"})
@Controller
public class NewCampaignController {
    //private static final Logger logger = LoggerFactory.getLogger(NewDealController.class);

    @Autowired
    private CampaignManager campaignManager;
    @Autowired
    private CityManager cityManager;
    @Autowired
    SimpleDateFormat dateFormat;
    @Autowired
    CustomDateEditor dateEditor;

    @RequestMapping(value = "campaign/new", method = RequestMethod.GET)
    public String showForm(Map<String, Object> model) {
        //List<Campaign> campaigns = campaignManager.getCampaigns();
        Campaign campaignForm = new Campaign();
        CampaignCities cities = new CampaignCities();
        cities.setCities(new HashSet<City>(cityManager.getCity()));
        //campaignForm.setCities(cities);
        model.put("campaignCities", cities);
        model.put("campaign", campaignForm);
        return "campaign/new";
    }

    @RequestMapping(value = "campaign/new", method = RequestMethod.POST)
    public String processForm(@Valid Campaign campaignForm, BindingResult result, Map<String,Object> model) {
        new CampaignValidator().validate(campaignForm, result);
        if (result.hasErrors()) {
            return "campaign/new";
        }
        this.campaignManager.saveCampaign(campaignForm);
        model.put("campaign", campaignForm);
        model.put("campaigns", this.campaignManager.getCampaigns());
        return "campaign/added";
    }

我能够让广告系列以表格形式呈现,并且我已成功使用以下方式呈现城市列表:

<form:checkboxes items="${campaignCities.cities}" path="cities" itemLabel="name" itemValue="id" delimiter="<br/>" />

但是,当我提交表单时,我收到以下验证错误。

  

字段'cities'上对象'campaign'中的字段错误:被拒绝的值   [2,1];代码   [typeMismatch.campaign.cities,typeMismatch.cities,typeMismatch.com.groupdealclone.app.domain.CampaignCities,typeMismatch];   参数   [org.springframework.context.support.DefaultMessageSourceResolvable:   代码[campaign.cities,cities];参数[];默认消息   [城市]];默认消息[无法转换类型的属性值   'java.lang.String []'到必需的类型   'com.groupdealclone.app.domain.CampaignCities'用于财产'城市';   嵌套异常是java.lang.IllegalStateException:无法转换   类型[java.lang.String []]的值为必需类型   [com.groupdealclone.app.domain.CampaignCities]属性'cities':   找不到匹配的编辑器或转换策略]

我试图想办法在SpringMVC 3中处理这个问题,但是我已经被困了一天没有成功。我只想在表单上检查的列表或集合或城市提交给控制器并添加到Campaign。如何解决转换问题,我可以将String []转换为List或City of City。

我正在开发的项目是一个公共GitHub项目,你可以下载源代码并使用Maven进行设置,如果你喜欢这个项目被称为Group-Deal-Clone

1 个答案:

答案 0 :(得分:1)

在差不多2天后,答案比我预期的要简单。感谢this thread我被引导回答。

在我的NewCampaignController中,我做了:

@InitBinder
public void initBinder(WebDataBinder binder) {
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, dateEditor);

    binder.registerCustomEditor(CampaignCities.class, "cities", new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            String [] ids = text.split(",");
            CampaignCities cities = null;
            for(String id:ids){
                if(cities == null)
                    cities = new CampaignCities();
                City city = cityManager.getCity(new Long(id));
                if(city != null)
                    cities.getCities().add(city);

            }
            if(cities != null){
                cities.setId(null);
                setValue(cities);
            }
        }
    });