SpringMVC 3 转换返回 String[] 到实体对象
我有一个与 CampaignCities 城市具有一对一关系的实体营销活动。 反过来,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();
营销活动城市实体
@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/>" />
但是,当我提交表单时,我收到以下验证错误。
字段“城市”上的对象“营销活动”中出现字段错误:值被拒绝 [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] 属性“城市”: 未找到匹配的编辑器或转换策略]
我试图找出一种在 SpringMVC 3 中处理这个问题的方法,但我已经被困了一天多,但没有成功。我只是想要一个在表单上检查的列表或集合或城市,将其提交到控制器并添加到营销活动中。如何解决转换问题,将返回的 String[] 转换为城市列表或城市集。
我正在开发的项目是一个公共 GitHub 项目,如果您喜欢该项目,您可以下载源代码并使用 Maven 设置它 团购克隆
I have an Entity Campaign that has a OneToOne relationship with CampaignCities cities.
In turn, CampaignCities contains a Set cities;
The campaign entity
@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();
The CampaignCities entity
@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;
}
}
The City entity:
@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;
}
}
My 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";
}
I have been able to get campaign to render in a form and I've rendered the list of cities successfully using:
<form:checkboxes items="${campaignCities.cities}" path="cities" itemLabel="name" itemValue="id" delimiter="<br/>" />
However when i submit the form, I get the following validation error.
Field error in object 'campaign' on field 'cities': rejected value
[2,1]; codes
[typeMismatch.campaign.cities,typeMismatch.cities,typeMismatch.com.groupdealclone.app.domain.CampaignCities,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [campaign.cities,cities]; arguments []; default message
[cities]]; default message [Failed to convert property value of type
'java.lang.String[]' to required type
'com.groupdealclone.app.domain.CampaignCities' for property 'cities';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [java.lang.String[]] to required type
[com.groupdealclone.app.domain.CampaignCities] for property 'cities':
no matching editors or conversion strategy found]
I've tried to figure out a way to handle this in SpringMVC 3 but I've been stuck for over a day with no success. I simply want a List or Set or Cities that where checked on the form to be submitted to the controller and added to the Campaign. How do I get around the conversion problem where I can convert the String[] returned to a List or Set of Cities.
The project I'm working on is a public GitHub project, you can download the source and set it up using Maven if you like the project is called Group-Deal-Clone
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
差不多两天后,答案比我想象的要简单。感谢此线程我被引导找到了答案。
在我的 NewCampaignController 中我做了:
After what is almost 2 days, the answer was simpler than I expected. Thanks to this thread I was guided to the answer.
In my NewCampaignController I did: