Concatenate strings in JSP EL?

2019-01-11 18:39发布

I have a List of beans, each of which has a property which itself is a List of email addresses.

<c:forEach items="${upcomingSchedule}" var="conf">
    <div class='scheduled' title="${conf.subject}" id="scheduled<c:out value="${conf.id}"/>">
    ...
    </div>
</c:forEach>

This renders one <div> per bean in the List.

For the sublist, what I'd like to be able to do is to concatenate each of the entries in the list to form a single String, to be displayed as a part of the <div>'s title attribute. Why? Because we are using a javascript library (mootools) to turn this <div> into a floating tool tip, and the library turns the title into the text of the tooltip.

So, if ${conf.subject} was "Subject", ultimately I'd like the title of the <div> to be "Subject: blah@blah.com, blah2@blah2.com, etc.", containing all of the email addresses of the sub-list.

How can I do this using JSP EL? I'm trying to stay away from putting scriptlet blocks in the jsp file.

标签: java jsp el taglib
8条回答
放荡不羁爱自由
2楼-- · 2019-01-11 19:04

You can use the EL 3.0 Stream API. For example if you have a list of strings,

<div>${stringList.stream().reduce(",", (n,p)->p.concat(n))}</div>

In case you have a list of objects for ex. Person(firstName, lastName) and you wish to concat only one property of them (ex firstName) you can use map,

<div>${personList.stream().map(p->p.getFirstName()).reduce(",", (n,p)->p.concat(n))}</div>

In your case you could use something like that (remove the last ',' also),

<c:forEach items="${upcomingSchedule}" var="conf">
    <c:set var="separator" value=","/>
    <c:set var="titleFront" value="${conf.subject}: "/>
    <c:set var="titleEnd" value="${conf.invitees.stream().reduce(separator, (n,p)->p.concat(n))}"/>
    <div class='scheduled' title="${titleFront} ${titleEnd.isEmpty() ? "" : titleEnd.substring(0, titleEnd.length()-1)}" id="scheduled<c:out value="${conf.id}"/>">
    ...
    </div>
</c:forEach>

Be careful! The EL 3.0 Stream API was finalized before the Java 8 Stream API and it is different than that. They can't sunc both apis because it will break the backward compatibility.

查看更多
唯我独甜
3楼-- · 2019-01-11 19:10

I think this is what you want:

<c:forEach var="tab" items="${tabs}">
 <c:set var="tabAttrs" value='${tabAttrs} ${tab.key}="${tab.value}"'/>
</c:forEach>

In this case, I had a hashmap with tab ID (key) and URL (value). The tabAttrs variable isn't set prior to this. So it just sets the value to the current value of tabAttrs ('' to start) plus the key/value expression.

查看更多
登录 后发表回答