gpt4 book ai didi

java - Spring-MVC:使用 'select-options' 时获取完整的对象而不是字符串

转载 作者:行者123 更新时间:2023-12-01 22:43:27 24 4
gpt4 key购买 nike

我有类Lesson,它保存对Course对象的引用,如下所示:

public class Lesson {
...
private Course course;
...
public Course getCourse() {
return course;
}

public void setCourse(Course course) {
this.course = course;
}
...
}

我想通过选择表单设置 Lesson 对象上的 Course 属性:

<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 中,我有以下内容:

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

...
}

问题在于它将 Course 对象的 String 表示形式(由 toString() 定义)传递给 course Lesson 对象的 setter。

如何使用我的选择表单正确设置 Lesson 对象的 Course 属性?

最佳答案

通常用于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);
}
}

关于java - Spring-MVC:使用 'select-options' 时获取完整的对象而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25731951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com