Spring没有使用我的转换器从String到我的对象

时间:2017-08-05 16:40:56

标签: java spring jsp spring-mvc

我从jsp表单获取自定义对象成绩时遇到问题:选择。

我把转换器给它并将其添加到我的bean中。 我错误地得到了对象的id,但我没有使用从String到我的对象Grade的转换器。

我收到错误:

Field error in object 'student' on field 'gradeId': rejected value [6]; codes [typeMismatch.student.gradeId,typeMismatch.gradeId,typeMismatch.com.michups.classregister.entity.Grade,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.gradeId,gradeId]; arguments []; default message [gradeId]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.michups.classregister.entity.Grade' for property 'gradeId'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.michups.classregister.entity.Grade' for property 'gradeId': no matching editors or conversion strategy found]

它似乎无法转换它。所以我得到null:

Field error in object 'someBean' on field 'gradeId': rejected value [null]; codes []; arguments []; default message [typeMismatch]

我的jsp页面中的表单: `

    <form:hidden path="studentId"/>

    <table>
        <tbody>

    <%-- other inpu field-%>
        <tr>
            <td><label>Grade:</label></td>
            <td><form:select path="gradeId">
                <form:options items="${grades}" itemLabel="number"
                    itemValue="gradeId"/>
            </form:select></td>
        </tr>
        <tr>
            <td><label></label></td>
            <td><input type="submit" value="Save" class="save"></td>

        </tr>
        </tbody>
    </table>
</form:form>`

我已经创建了一个转换器但不知何故春天没有使用它:

public class GradeConverter implements Converter<String, Grade> {

    @Autowired
    private GradeService gradeService;

    public Grade convert(String id){
        return gradeService.getGrade(Integer.valueOf(id));
    }
}

将它添加到我的bean:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.michups.classregister.converter.GradeConverter"/> </list> </property> </bean>

使用:

<mvc:annotation-driven/>

并将我的转化服务添加到控制器:

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private ConversionService conversionService



    @Autowired
    private StudentService studentService;
    @Autowired
    private GradeService gradeService;


    @GetMapping("/showFormAdd")
    public String showFormAdd(Model model){

        List<Grade> grades = gradeService.getGrades();


        model.addAttribute("grades", grades);

        Student student= new Student();
        model.addAttribute("student", student);
        return "form-students";
    }
    @PostMapping("/saveStudent")
    public String saveStudent(@ModelAttribute("student") Student student,
                          BindingResult errors){
        if(errors.hasErrors()){
            System.out.println("ERRORR");
        System.out.println(errors);
        for (FieldError error : errors.getFieldErrors()) {
            System.out.println(new FieldError("someBean", error.getField(), error.getCode()));
        }
    }
    else {
        student.toString();
        studentService.saveStudent(student);
    }
    return "redirect:/student/list";
}

Student对象里面有Grade对象:

@Getter
@Setter
@Entity
@Table(name = "student")
public class Student  implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private Integer studentId;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "grade_id", nullable = false)
    public Grade gradeId;

    @Column(name = "birth_date")
    @DateTimeFormat(pattern = "dd-MM-yyyy")
    private Date birthDate;
}


@Getter
@Setter
@Entity
@Table(name = "grade")
public class Grade implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "grade_id")
    private Integer gradeId;

    @Column(name = "number")
    private Integer number;

    @Column(name = "alfabet_digit")
    private String alfabetDigit;

    @Column(name = "year")
    @DateTimeFormat(pattern = "yyyy")
    private Integer year;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "teacher_grade",  joinColumns = {
        @JoinColumn(name = "grade_id", nullable = false, updatable = false) },
        inverseJoinColumns = { @JoinColumn(name = "teacher_id",
                nullable = false, updatable = false) })
    public Set<Teacher> teachers = new HashSet<>(0);
}

我不知道,也无法找到我做错的事。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我在stackoverflow页面https://stackoverflow.com/a/29210517/6416954上找到了解决方案。但是,我看到了很多这方面的解决方案,但这样的方法对我有用。

我删除了我的转换器并创建了格式化程序:

@Component
public class GradeFormatter implements Formatter<Grade> {
    @Autowired
    private GradeService gradeService;
    @Override
    public String print(Grade grade, Locale locale) {
        return grade.getNumber() + grade.getAlfabetDigit();
    }
    @Override
    public Grade parse(String s, Locale locale) throws ParseException {
        return gradeService.getGrade( Integer.valueOf(s) );
    }
}

我将此添加到我的bean中,因为它在链接中的答案中显示:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="formatters">
        <set>
            <ref bean="gradeFormatter" />
        </set>
    </property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" />

现在一切都很好。