【发布时间】:2014-11-10 15:57:53
【问题描述】:
首先:我是 Spring 的初学者,这是我第一次尝试使用 Spring MVC 实现 Web 应用程序。 这是我所做的:
实体:
@Entity
@Table(name = "coins")
public class Coin
{
@Id
@GeneratedValue
private Integer id;
@OneToOne
private Country country;
private double value;
private int year;
}
@Entity
@Table(name = "countries")
public class Country
{
@Id
@GeneratedValue
private Integer id;
private String name;
}
控制器:
@Controller
public class CoinViewController {
@Autowired
private CoinService service;
@Autowired
private CountryService countryService;
@ModelAttribute("countries")
public List<Country> frequencies() {
return countryService.get();
}
@RequestMapping(value = "/coins/add", method = RequestMethod.GET)
public String addCoin(Model model) {
model.addAttribute("coin", new Coin());
return "coins/add";
}
@RequestMapping(value = "/coins/add", method = RequestMethod.POST)
public String addCoinResult(@ModelAttribute("coin") Coin coin, BindingResult result) {
// TODO: POST HANDLING
return "/coins/add";
}
}
JSP:
<form:form action="add" method="POST" modelAttribute="coin">
<div class="form-group">
<label for="country">Country:</label>
<form:select path="country" class="form-control" >
<form:option value="" label="-- Choose one--" />
<form:options items="${countries}" itemValue="id" itemLabel="name" />
</form:select>
</div>
<div class="form-group">
<label for="value">Value:</label>
<form:input path="value" class="form-control" />
</div>
<div class="form-group">
<label for="year">Year:</label>
<form:input path="year" class="form-control" />
</div>
<button type="submit" value="submit" class="btn btn-default">Erstellen</button>
</form:form>
但是当我尝试保存来自 JSP 的输入时,我总是得到这个:
字段“国家”上的对象“硬币”中的字段错误:拒绝值 [1]; 代码 [typeMismatch.coin.country,typeMismatch.country,typeMismatch.Country,typeMismatch]; 论据 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [coin.country,country];论据 [];默认消息 [国家]];默认消息 [无法转换类型的属性值 'java.lang.String' 到属性'country' 所需的类型'Country'; 嵌套异常是 java.lang.IllegalStateException: 无法转换 类型 [java.lang.String] 到所需类型 [Country] 的值 属性“国家/地区”:未找到匹配的编辑器或转换策略]
所以我的问题是:
- 我应该使用什么编辑器/转换器?
- 如何在我的 Controller 中注册其中一个?
【问题讨论】:
标签: java spring jsp spring-mvc