How to use square bracket in EL JSF
Asked Answered
A

1

5

I have seen people using square bracket in JSF, and I am not sure if I understand its use correctly. So maybe an JSF guru can help me understand it

1.So let say I have this

#{bean.x}

and x is a two dimensional array (x[][]), how do I display x[0] using EL? I would imagine that I need to use square bracket in this case. I think I use #{bean.x[0]}, but I got exception.

2.The second scenario is from BalusC code Pass Argument to a composite-component action attribute

<composite:interface>
   <composite:attribute name="bean" type="java.lang.Object" />
   <composite:attribute name="action" type="java.lang.String" />
   <composite:attribute name="property" type="java.lang.String" />
</composite:interface>
<composite:implementation>
   <h:commandButton value="Remove" action="#{cc.attrs.bean[cc.attrs.action]}">
      <f:setPropertyActionListener target="#{cc.attrs.bean[cc.attrs.property]}" value="Somestring" />
   </h:commandButton>
</composite:implementation>

I understand what the code is doing and it works beautifully, but I would appreciate if someone can explain what is the use of the square bracket in this case. Thank you very much

Amylopectin answered 9/9, 2012 at 22:11 Comment(1)
For the second part, cc.attrs is the map of parameters passed to the composition by the page. If bean has value myBean and action has value myAction, then #{cc.attrs.bean[cc.attrs.action]} would be the equivalent to #{myBean.myAction} (but passed as attributes to a composite, of course.Breastwork
P
10

I think I use #{bean.x[0]}, but I got exception.

It's unfortunate that you didn't share the exception details. But this should just work, provided that there's a getX() method which returns a non-null array of which the given index really exists.


The second scenario is from BalusC code Pass Argument to a composite-component action attribute

In this particular case, the brace notation [] enables you to use a dynamic property name or action method name. The following of course don't work

#{cc.attrs.bean.cc.attrs.action}

It would only try to invoke bean.getCc().getAttrs().action().

The brace notation is also used on Map<K, V>. It allows you to specify keys which contain dots (which in turn shouldn't be EL-evaluated as properties)

#{bean.map['key.with.dots']}

It of course also allows you to specify a dynamic map key:

#{bean.map[otherBean.mapKey]}

See also:

Precatory answered 9/9, 2012 at 23:57 Comment(1)
I think I use #{bean.x[0]}, but I got exception. This in fact does work. I wrote a small test case, and it works as expected. The exception was something else. Thank you for your insightAmylopectin

© 2022 - 2024 — McMap. All rights reserved.