无法转换类型' java.lang.String'的属性值

时间:2017-09-29 16:44:19

标签: spring spring-mvc thymeleaf

我在这里做错了什么?

<select th:field="*{role}">
    <option value="#" disabled="disabled" selected="selected">Role...</option>
    <option th:each="r : ${roles}" th:value="${r}" th:text="${r.name}">Developer</option>
</select>

我收到此错误:

Field error in object 'collaborator' on field 'role': rejected value
[33]; codes
[typeMismatch.collaborator.role,typeMismatch.role,typeMismatch.com.imprender.instateam.model.Role,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [collaborator.role,role]; arguments []; default message [role]];
default message [*Failed to convert property value of type
'java.lang.String' to required type
'com.imprender.instateam.model.Role' for property 'role'*; nested
exception is java.lang.IllegalStateException: Cannot convert value of
type 'java.lang.String' to required type
'com.imprender.instateam.model.Role' for property 'role': no matching
editors or conversion strategy found]

它说:

**Failed to convert property value of type 'java.lang.String' to required type 'com.imprender.instateam.model.Role' for property
'role'**

但我不明白我在做什么。

我认为我没有正确传输中选择的值。我认为发送的对象将是value选项中声明的对象被选中,但显然我弄错了,无法找到正确的方法。

模特:

package com.imprender.instateam.model;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Entity
public class Collaborator {

    @Id
    //Todo: check strategy
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Pattern(regexp = "([A-Z][a-zA-Z]*\\s*)+")
    private String name;

    //Todo: check, do we want to create a new table to associate values?

    @NotNull
    @ManyToOne
    private Role role;

    public Collaborator() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }
}

2 个答案:

答案 0 :(得分:1)

你的问题是在你的选择中说该字段是一个角色,实体类型为Role,但在你的选项中,值是一个ID,一些原始值,然后不匹配。你可以改成这个

<select th:field="*{role.id}">
    <option value="#" disabled = "disabled" selected="selected">Role...</option>
    <option th:each="r : ${roles}" th:value="${r.id}" th:text="${r.name}">Developer</option>
</select>

答案 1 :(得分:0)

无法将类型java.lang.String[]的属性值转换为属性int的必需类型aid

我的jsp代码如下:-

<form action = "getaction">
<input type ="text" name="aid"><br/>
<input type = "submit"><br/>