Have you come across an exception of the type below?
Field error in object 'student' on field 'courseList': rejected value [mad.nurseryapplication.model.Course@0]; codes [typeMismatch.student.courseList,typeMismatch.courseList,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.courseList,courseList]; arguments []; default message [courseList]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'courseList'
Well this type of exception is usual for spring developers. As the exception clearly suggests, it is a case of spring not being able to convert the data type. Take a look at the below code.
<form:hidden path="id" value="${student.id}"/>
<c:forEach items="${avacourses}" var="course" varStatus="status">
<tr><td><form:checkbox path="courseList" value="${course}" /></td>
<td>${course.courseName}</td></tr></c:forEach>
Here you can see that the value is ${course} which is an object. How ever spring understands this as
a string. So in such a case you need to convert type string to course type. look at below code.
<form:hidden path="id" value="${student.id}"/>
<c:forEach items="${avacourses}" var="course" varStatus="status">
<tr><td><form:checkbox path="courseList" value="${course.id}" /></td>
<td>${course.courseName}</td></tr></c:forEach>
Note that the value is now ${course.id}. Usually id is a long type. How ever still spring takes this as a string. So we need to have a converter. The converter class is shown below.
final public class StringToCourse implements Converter<String, Course>{
@Autowired
CourseService courseService;
@Override
public Course convert(String source) {
return courseService.getCourseById(Long.valueOf(source));
}
}
How ever we need to make sure that the application knows that this converter is available when needed. So put the following code in your context file.
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="mad.nurseryapplication.util.StringToCourse" />
</list>
</property>
</bean>
Also make sure that you put xml schema related info for mvc in the beans tag. That's all !!!
No comments:
Post a Comment