首先:我是Spring的初学者,这是我第一次尝试用Spring实现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保存输入时,我总是得到以下内容:
字段'Country‘上的对象’硬币‘中的字段错误:拒绝值1;代码typeMismatch.coin.country、typeMismatch.country、typeMismatch.Country、typeMismatch;参数typeMismatch.country代码coin.country,country;参数[];默认消息国家];默认消息[未能将'java.lang.String’类型的属性值转换为属性‘country’所需的类型'country';嵌套的例外是java.lang.IllegalStateException:无法将类型java.lang.String的值转换为属性“Country”所需的类型国家:没有找到匹配的编辑器或转换策略]
所以我的问题是:
发布于 2014-09-16 19:46:16
您可以将自定义编辑器注册到控制器类的initBinder中:
@Controller
public class CoinViewController {
@Autowired
private CountryEditor countryEditor;
@InitBinder
protected void initBinder(final WebDataBinder binder, final Locale locale) {
binder.registerCustomEditor(Country.class, countryEditor);
}
......
}(在本例中不需要locale参数,但如果需要区域设置来进行转换-例如,如果您正在处理日期,则可能很有用)
您可以定义CountryEditor,如下所示:
@Component
public class CountryEditor extends PropertyEditorSupport {
@Autowired
private CountryService countryService;
@Override
public void setAsText(final String text) throws IllegalArgumentException {
try{
final Country country = countryService.findById(Long.parseLong(text));
setValue(cliente);
}catch(Exception e){
setValue(country);
// or handle your exception
}
}
}我让spring用@Component注释处理编辑器的注入。因此,如果您喜欢这样做,记得启用该类的包扫描!
希望能帮上忙!
https://stackoverflow.com/questions/25876601
复制相似问题