我正在尝试在我的 Spring Web 应用程序中使用 Converter。这是代码:
public class RoleConverter implements Converter<String, Role> {
@Autowired
private RoleService roleService;
public Role convert(String id) {
return roleService.getRole(Integer.parseInt(id));
}
}
我已经配置了相应的xml:
<mvc:annotation-driven conversion-service="conversionService" />
<beans:bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<beans:property name="converters">
<beans:set>
<beans:bean class="net.schastny.contactmanager.converters.RoleConverter"/>
</beans:set>
</beans:property>
</beans:bean>
我也尝试class="org.springframework.context.support.ConversionServiceFactoryBean"
改用
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
但没有任何帮助。我总是遇到一个例外:
无法将类型 [java.lang.String] 的值转换为属性“角色”所需的类型 [net.schastny.contactmanager.domain.Role]:找不到匹配的编辑器或转换策略]
请帮助我认识到我做错了什么。我花了大约 16 个小时来解决这个问题,但没有任何帮助:(
UPD 好的,这是发生了什么的简短解释:我有包含角色类(一对多)的用户类,并且想要编写允许创建具有角色的用户的jsp,我使用下拉列表来选择角色:
<form:form method="post" action="add" commandName="user">
Login: <form:input path = "login" value = "" />
Password: <form:input path = "password" value = "" />
Select role:
<form:select path="role">
<form:options items="${roleList}" itemValue="id" itemLabel="description"/>
</form:select>
<input type="submit" value = "add">
</form:form>
so the idea is that after submitting I have Id of the Role so i want to get Role by its Id using Converter. The code of method that causes exception is extremely easy:
@RequestMapping("/add")
public String home(@ModelAttribute User user) {
System.out.println(user.getRole().getDescription());
System.out.println(user.getLogin());
System.out.println(user.getPassword());
return "redirect:/index";
}