gpt4 book ai didi

java - 以 Spring MVC 形式绑定(bind)的对象

转载 作者:行者123 更新时间:2023-11-30 05:53:50 24 4
gpt4 key购买 nike

我正在使用 Spring MVC 开发一个测试应用程序。我有一个 Person 类和一个 Group 类。每个 Person 对象都引用一个 Group 对象。

现在我实现了一个显示人员数据并允许编辑的 jsp。在我的表单中,我放置了一个选择控件来选择 pearson 的组:

<sf:select path="group">
<sf:options items="${groupList}" itemLabel="name" itemValue="id" />
</sf:select>

当我加载页面时它显示正确的组,但我无法保存更改,因为在 Controller 中我只得到代表组 id 的字符串。

所以,我的问题是:如何在我的 Controller 中获取 Group 对象而不是它的 id?

更新这是我的 Controller 代码:

@RequestMapping(value = "/details", params = "save", method = RequestMethod.POST)
public String save(@ModelAttribute("person") Person p,
BindingResult result) {
this.personManager.savePerson(p);
return "redirect:/people/details?id=" + p.getId();
}

最佳答案

通过扩展 PropertyEditorSupport 创建您自己的 GroupEditor(它将正确填充组对象实例)。然后将其绑定(bind)到您的 Controller 中:

@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Group.class, new GroupEditor(groupService));
}

您的实际编辑器可能看起来像这样:

public class GroupEditor extends PropertyEditorSupport{

private final GroupService groupService;

public GroupEditor(GroupService groupService){
this.groupService= groupService;
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
Group group = groupService.getById(Integer.parseInt(text));
setValue(group);
}
}

Spring docs

关于java - 以 Spring MVC 形式绑定(bind)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10138715/

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