JSP EL:动态创建属性名称
我试图使用JSP动态生成内容。
我有一个循环,我在其中动态创建bean访问器。 骨架类似于:
${bean.table} // append 'type' to the "table" property
我的问题是:我想根据类型更改${bean.table}
。 例如,如果类型是{"Janitor", "Chef}
,我想生产:
${bean.tableJanitor} ${bean.tableChef}
我怎样才能做到这一点?
您可以使用大括号[]
来使用动态键访问bean属性。
${bean[property]}
所以,根据你的例子:
${bean[property]}
如果您需要以动态方式访问复杂字段,则可以执行以下操作:
并在SomeOtherBean类中实现invokeELGetter:
public Object invokeELGetter(String el) { FacesContext facesContext = FacesContext.getCurrentInstance(); ELContext elContext = facesContext.getELContext(); ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory(); ValueExpression exp = expressionFactory.createValueExpression(elContext, el, Object.class); return exp.getValue(elContext); }
请注意,这需要EL 2.2(Tomcat 7用于使用Tomcat的用户)。