我正在尝试在 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">
但没有任何帮助。我总是遇到异常(exception):
Cannot convert value of type [java.lang.String] to required type [net.schastny.contactmanager.domain.Role] for property 'role': no matching editors or conversion strategy found]
请帮助我认识到我做错了什么。我花了大约 16 个小时来解决这个问题,但没有任何帮助:(
UPD 好的,这是发生的事情的简短解释:我有包含角色类(一对多)的 User 类,并且想要编写允许使用角色创建用户的 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>
所以想法是,提交后我有角色的 ID,所以我想使用转换器通过其 ID 获取角色。 引发异常的方法代码非常简单:
@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";
}
最佳答案
你能打印什么吗 roleService.getRole(Integer.parseInt(id)) 正在返回。它是否返回一个无法转换为角色对象的字符串。
关于java - Spring 没有看到转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752279/