春天看不到转换器

时间:2013-05-25 17:44:20

标签: java spring

我正在尝试在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]属性'role':没有   找到匹配的编辑器或转换策略]

请帮助我认识一下我做错了什么。我花了大约16个小时来解决问题,但没有任何帮助:(

UPD 好的,这里有简短的解释:我有User类,其中包含Role类(一对多),并希望编写允许创建User with Role的jsp,并使用dropdown选择Role:

<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使用Converter获得角色。 导致异常的方法代码非常简单:

@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";
}

2 个答案:

答案 0 :(得分:0)

你能打印什么吗?     roleService.getRole(的Integer.parseInt(ID)) 正在回归它是否返回一个无法转换为角色对象的字符串。

答案 1 :(得分:0)

所以几个小时后我的头靠在墙上,我找到了解决办法。这里是: spring 3.0 Custom generic converter not found though registered.Error: no matching editors or conversion strategy found 我有同样的问题。希望有人不会花20个小时来解决它:)

相关问题