我正在尝试创建一个简单的 crud 表单,以在不知道对象类型是什么的情况下,使用 hibernate 将数据插入数据库。最终目标是数据库中的每个表只有一个插入表单。到目前为止,我得到了当前对象的方法,检查它是否有任何设置的方法,并为每个有设置的字段创建一个文本输入。
UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
HtmlPanelGrid hpg = (HtmlPanelGrid) viewRoot.findComponent("panel");
for (Method method : declaredFields) {
String name = method.getName();
if (name.contains("set")) {
HtmlOutputText hot = new HtmlOutputText();
HtmlInputText hit = new HtmlInputText();
hot.setValue(name.substring(3));
try {
hit.setValue(newObject.getClass().getMethod(name, String.class));
} catch (Exception ex) {
Logger.getLogger(ReflectController.class.getName()).log(Level.SEVERE, null, ex);
}
hpg.getChildren().add(hot);
hpg.getChildren().add(hit);
}
}
这里的newObject是后面hibernate要插入到数据库中的对象。我的问题是:
如何将该对象的某个字段分配给当前正在创建的文本输入。到目前为止,如果我像上面那样将方法放入值中,它只会打印出该输入的值属性中的方法。我想要的是,当提交此表单时,将该文本框中的值分配给具有该名称的属性。
最佳答案
我可以给你一个部分答案——你需要动态创建一个 ValueExpression
Application app = FacesContext.getCurrentInstance().getApplication();
hit.setValueExpression("value", app.getExpressionFactory().createValueExpression(FacesContext.getCurrentInstance().getELContext(), "#{bean.item}", Item.class));
困难的部分是创建将实际映射到对象值中的字段的 valueExpression。这需要更多思考,但您肯定需要动态 valueExpression。如所写,这将导致您的 bean 的 setItem(); 方法的执行带有 Item 类型的参数。您将需要一些更复杂的东西。
关于java - 使用 Java 反射动态创建 JSF 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11976201/