我有一个类Lesson
,它保存对Course
对象的引用,如下所示:
public class Lesson {
...
private Course course;
...
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
...
}
我想通过选择表单在Course
对象上设置Lesson
属性:
<form:form method="post" action="addLesson" modelAttribute="lesson">
<form:select path="course">
<form:options items="${courses}"/>
</form:select>
<input type="submit" name="addLesson" value="Add lesson">
</form:form>
在我的控制器中,我有以下内容:
@Controller
public class LessonController {
@Autowired
private LessonRepository lessonRepository;
@Autowired
private CourseRepository courseRepository;
// form setup
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showSchedule(ModelMap model) {
...
model.addAttribute("lesson", new Lesson());
model.addAttribute("courses", courseRepository.findAll());
...
}
@RequestMapping(value = "/addLesson", method = RequestMethod.POST)
public String addLesson(@ModelAttribute("lesson") Lesson lesson, BindingResult result) {
lessonRepository.save(lesson);
return "redirect:/";
}
...
}
问题是它将String
对象的Course
表示(由toString()
定义)传递给course
对象的Lesson
setter。
如何使用我的选择表单正确设置Course
对象的Lesson
属性?
答案 0 :(得分:1)
根据spring documentation,您需要在itemValue
标记上设置itemLabel
和form:options
,否则,正如您已经提到的,该值将是{{1}对象的toString()
和itemValue
应引用itemLable
bean中的属性。
假设您的Course
类有一个属性Course
,那么您的表单应如下所示:
name
答案 1 :(得分:1)
您可以使用Spring Converters直接绑定课程对象而不是某些课程对象属性。
实现Converter接口,在您的情况下可以将所选的courseName转换为Course:
public class CourseConverter implements Converter<String, Course> {
public Course convert(String source) {
List<Course> courseList = //Populate courseList the way you did in Lesson
Course course = //Get course object based on selected courseName from courseList;
return course;
}
}
现在注册转换器:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" >
<property name="converters">
<set>
<bean class="your.package.CourseConverter"/>
</set>
</property>
</bean>
并更改您的表单:选项为:
<form:options items="${courses}" itemValue="courseName" itemLabel="courseName"/>
答案 2 :(得分:1)
通常,对于UI呈现,Formatter<T>
与ConversionService一起使用。但是在Spring 3之前,使用了PropertyEditors
。
我已为您的案例分享了示例github项目https://github.com/jama707/SpringSelectBoxSample
@Component("courseFormatter")
public class CourseFormatter implements Formatter<Course> {
private CourseRepository courseRepository=new CourseRepository();
@Override
public String print(Course course, Locale arg1) {
return course.getName();
}
@Override
public Course parse(String actorId, Locale arg1) {
return courseRepository.getCourse(actorId);
}
}