我有两张表:公司和汽车。一家公司可以有很多辆汽车。我不能正确地持久化汽车。从下拉列表中选择查看页面中的公司。
我的控制器
@RequestMapping("/")
public String view(ModelMap model) {
Map<String, String> companyList = new HashMap<String, String>();
List<Company> companies = companyService.listAllCompanies();
for (Company company : companies) {
companyList.put(String.valueOf(company.getId()), company.getName());
}
model.addAttribute("companies", companyList);
model.addAttribute("automotive", new Automotive());
return "automotive/index";
}
@RequestMapping("manage")
public String manage(@ModelAttribute Automotive automotive,
BindingResult result, ModelMap model) {
model.addAttribute("automotive", automotive);
Map<String, String> companyList = new HashMap<String, String>();
List<Company> companies = new ArrayList<Company>();
for (Company company : companies) {
companyList.put(String.valueOf(company.getId()), company.getName());
}
model.addAttribute("companies", companyList);
automotiveService.addAutomotive(automotive);
return "automotive/index";
}我的观点
<form:form action="/Automotive/manage" modelAttribute="automotive">
Name : <form:input path="name" />
Description : <form:input path="description" />
Type : <form:input path="type" />
Company : <form:select path="company" items="${companies}" />
<input type="submit" />
</form:form>从逻辑上讲,正如预期的那样,公司id不会被保存,因为在这里它是一个id,但实际上在保存它的时候应该是一个类型为Q1>的对象。我该如何解决这个问题。我需要使用DTO吗?或者有什么直接的方法吗?
Q2>不能直接将公司列表传递给视图,而不是在控制器中创建新的地图吗?
发布于 2013-05-09 02:12:24
您可以使用公司的id作为关键字,然后使用converter,它会自动将数据从表单转换为域对象。就像下面的代码一样:
public class CompanyIdToInstanceConverter implements Converter<String, Company> {
@Inject
private CompanyService _companyService;
@Override
public Company convert(final String companyIdStr) {
return _companyService.find(Long.valueOf(companyIdStr));
}
}在JSP中:
<form:select path="company" items="${companies}" itemLabel="name" itemValue="id"/>如果你还没有接触到这一点,你可能需要阅读更多关于类型转换的内容。Spring doc中对此进行了完美的描述(我,你找不到:http://static.springsource.org/spring/docs/3.0.x/reference/validation.html,第5.5段)。
我希望它能对你有所帮助。
https://stackoverflow.com/questions/16447335
复制相似问题