EL conditional Method Expression

梦想与她 提交于 2019-12-01 05:47:47

问题


I would like to declare a conditional method expression in EL like below:

<p:dataTable id="#{cc.attrs.datatableId}" var="overview" 
    rowSelectListener="#{cc.attrs.detailsMode == 'single' ? cc.attrs.bean.onRowSelect : cc.attrs.bean.onRowUrlSelect}">

However, it throws an EL exception:

javax.el.ELException: Not a Valid Method Expression: #{ cc.attrs.detailsMode == 'single' ? cc.attrs.bean.onRowSelect : cc.attrs.bean.onRowUrlSelect}

How I can declare a conditional EL method expression?


回答1:


Unfortunately, method expressions does not accept value expressions. Your best bet is to have a single method entry point which in turn delegates further to the desired action methods based on the detailsMode which you also pass/set to the bean.

E.g.

<h:dataTable ... rowSelectListener="#{cc.attrs.bean.onRowSelect}">
 public void onRowSelect(SelectEvent event) {  
     if ("single".equals(detailsMode)) {
         onRowSingleSelect(event);
     } else {
         onRowUrlSelect(event);
     }
 }

Given that you're actually using a composite component, you can if necessary hide it away in the backing component to reduce boilerplate in backing bean:

<cc:interface componentType="yourComponent">
...
<h:dataTable ... rowSelectListener="#{cc.onRowSelect}">
@FacesComponent("yourComponent")
public class YourComponent extends UINamingContainer {

     public void onRowSelect(SelectEvent event) {  
        String methodName = "single".equals(detailsMode) ? "onRowSingleSelect" : "onRowUrlSelect";
        MethodExpression method = (MethodExpression) getAttributes().get(methodName);
        method.invoke(getFacesContext().getELContext(), new Object[] { event });
     }

}



回答2:


You can try with

<p:dataTable id="#{cc.attrs.datatableId}" var="overview" 
    rowSelectListener="#{cc.attrs.bean[cc.attrs.detailsMode == 'single' ? 'onRowSelect' : 'onRowUrlSelect']}">

For further reference, you can refer to https://docs.oracle.com/javaee/6/tutorial/doc/bnahu.html#bnahz



来源:https://stackoverflow.com/questions/5433876/el-conditional-method-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!