gpt4 book ai didi

java - Spring自动绑定(bind)bean属性的下拉列表

转载 作者:行者123 更新时间:2023-12-01 17:39:54 24 4
gpt4 key购买 nike

有没有办法使用 spring 的 form.select 来绑定(bind)另一种类型的 bean 的 bean 属性。示例:

我有一个 Bean 需要在 View 中使用名为 BeanB 的属性进行更新:

public class BeanA {    
private BeanB bean;
private int id;

private void setId(int id){
this.id = id;
}

private int getId(){
return this.id;
}

public void setBean(BeanB bean){
this.bean = bean;
}

public BeanB getBean(){
return this.bean;
}
}

public class BeanB{
private int id;

private void setId(int id){
this.id = id;
}

private int getId(){
return this.id;
}
}

对于 View ,我想发送一个 BeanB 列表,以便使用 spring 的表单 Controller 进行选择:

public class MyController extends SimpleFormController{

protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception {
BeanA bean = new BeanA();
//... init the bean or retrieve from db

List<BeanB> list = new ArrayList<BeanB>();
//... create list of objects

ModelAndView modelAndView = super.handleRenderRequestInternal(request, response);
modelAndView.getModel().put("beans", list);
modelAndView.getModel().put("bean", bean);

return modelAndView ;
}
}

在jsp中,我想使用form.select从给定列表中选择我想要为BeanA设置的项目,例如:

<form:select path="${bean.bean}" items="${beans}"/>

看来这样不行。有其他简单的解决方案吗?

最佳答案

要在 HTML 中创建选择标记:

<form:select path="bean" items="${candidates}" itemValue="id" itemLabel="name"/>

提交表单时,该值将以字符串形式传递到 Spring,然后需要将其转换为所需类型的 bean。 Spring 为此使用 WebDataBinder,使用 PropertyEditors 进行与字符串的转换。由于您的“id”属性可能已经可以序列化为字符串,因此您已经看到了一半的工作。

您正在寻找这个:http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-ann-webdatabinder

@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(BeanB.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
// some code to load your bean..
// the example here assumes BeanB class knows how to return
// a bean for a specific id (which is an int/Integer) by
// calling the valueOf static method
// eg:
setValue(BeanB.valueOf(Integer.valueOf(text)));
}
});
}

Spring 2.5.6 的文档似乎建议 @Controller 和 @InitBinder 注释在配置后有效,您必须根据您的环境进行推断。

@参见http://static.springsource.org/spring/docs/2.5.6/api/index.html?org/springframework/web/bind/WebDataBinder.html

关于java - Spring自动绑定(bind)bean属性的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280875/

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