开发者

NumberFormatException when trying to concatenate a String in EL

开发者 https://www.devze.com 2023-03-05 23:16 出处:网络
This is what I\'m trying to generate: <div class=\"marker\" style=\"background:transparent url(\'/myApp/faces/javax.faces.resource/1.png?ln=images/map\') no-repeat center top;\"></div>

This is what I'm trying to generate:

<div class="marker" style="background:transparent url('/myApp/faces/javax.faces.resource/1.png?ln=images/map') no-repeat center top;"></div>
<div class="marker" style="background:transparent url('/myApp/faces/javax.faces.resource/2.png?ln=images/map') no-repeat center top;"></div>
<div class="marker" style="background:transparent url('/myApp/faces/javax.faces.resource/3.png?ln=images/map') no-repeat center top;"></div>

etc...

Here's my code:

<ui:repeat value="#{myBean.items}" var="item" varStatus="status">
    <h:panelGroup layout="block" styleClass="marker" style="background:transparent url(#{resource['images/map:'+(status.index+1)+'.png']} no-repeat center top;"/>
</ui:repeat>

This is failing with a NumberFormatException because the EL interpreter attempts to convert "images/m开发者_StackOverflow中文版ap" to a number. After searching quite a bit, I found that + is only for adding numbers. Any ideas how to achieve the desired results?


EL does not recognize the + operator as String concatenation operator. The + operator is in EL ultimately to sum numbers only. You need to use <ui:param> to create another expression variable wherein you concatenate the parts by just inlining the EL expression in the value and then use it in the final expression instead.

<ui:repeat value="#{myBean.items}" var="item" varStatus="status">
    <ui:param name="key" value="images/map#{status.index + 1}.png" />
    <h:panelGroup layout="block" styleClass="marker" style="background:transparent url(#{resource[key]} no-repeat center top;"/>
</ui:repeat>

Note: if you were using JSP instead of Facelets, you'd have used JSTL <c:set> instead of Facelets <ui:param>.


You can use concat function to concatenate strings in JSP EL. In your example that would be:

<ui:repeat value="#{myBean.items}" var="item" varStatus="status">
    <h:panelGroup layout="block" styleClass="marker" style="background:transparent url(#{resource['images/map:'.concat( (status.index+1).concat('.png')]} no-repeat center top;"/>
</ui:repeat>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号