gpt4 book ai didi

java - 在 apache wicket 中获取对象模型的原因是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:27 25 4
gpt4 key购买 nike

我是 apache wicket 的新手,我不明白为什么我们要获取对象的模型。例如,我们在网页的表单组件中获取类电影的模型,以保存提交的输入;

<code>CompoundPropertyModel model = new CompoundPropertyModel(movie);
this.setModel(model);
this.add(new TextField("title"));
this.add(new TextField("year"));</code>
代码继续;

@Override
public void onSubmit() {
Movie movie = (Movie) this.getModelObject();
WicketApplication app = (WicketApplication) this.getApplication();
MovieCollection collection = app.getCollection();
collection.addMovie(movie);
this.setResponsePage(new MovieDisplayPage(movie));
}

最佳答案

至少可以说,CompoundPropertyModel 是一个有争议的模型。它看起来就像魔术一样,并且具有一些不可预见的语义。

CompoundPropertyModel 的 JavaDoc 确实说明了一切:

/**
* A simple compound model which uses the component's name as the property expression to retrieve
* properties on the nested model object.
*
* CompoundPropertyModel is a chaining model so it will call get/setobject on the given object if
* the object is an instanceof IModel itself.
*
* @see org.apache.wicket.model.IModel
* @see org.apache.wicket.model.Model
* @see org.apache.wicket.model.LoadableDetachableModel
* @see IChainingModel
*
* @author Jonathan Locke
*
* @param <T>
* The model object type
*/
public class CompoundPropertyModel<T> extends ChainingModel<T> implements IComponentInheritedModel<T>

神奇之处在于属性路径的解析。具有 null 模型的 TextField 将查找组件层次结构,以查看是否存在具有 IComponentInheritedModel(CompoundPropertyModel 实现)的父级。如果是这样,它将使用它来评估组件标识符作为基于CompoundPropertyModel(最内部)对象的根的属性表达式。

这样你就可以做这样的事情:

setModel(new CompoundPropertyModel(person));
add(new TextField("spouse.familyName"));
add(new TextField("children[0].age"));

非常简洁,但也被认为是神奇的。

危险在于以下代码:

setModel(new CompoundPropertyModel(person));
add(new TextField("spouse.familyName"));
add(new TextField("children[0].age"));
add(new Link<Person>("delete") {
@Override
public void onClick() {
Person p = getModelObject();
if(p.isUnderage()) {
p.delete();
}
}
});

当链接检索其模型对象时,它将在未成年检查之前触发 Person 的 delete() 方法。所以要小心CompoundPropertyModel。

关于java - 在 apache wicket 中获取对象模型的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925218/

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