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 18:54

The "clean" way to do this would be to use a function. As the JSTL join function won't work on a Collection, you can write your own without too much trouble, and reuse it all over the place instead of cut-and-pasting a large chunk of loop code.

You need the function implementation, and a TLD to let your web application know where to find it. Put these together in a JAR and drop it into your WEB-INF/lib directory.

Here's an outline:

com/x/taglib/core/StringUtil.java

package com.x.taglib.core;

public class StringUtil {

  public static String join(Iterable<?> elements, CharSequence separator) {
    StringBuilder buf = new StringBuilder();
    if (elements != null) {
      if (separator == null)
        separator = " ";
      for (Object o : elements) {
        if (buf.length() > 0)
          buf.append(separator);
        buf.append(o);
      }
    }
    return buf.toString();
  }

}

META-INF/x-c.tld:

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
  <tlib-version>1.0</tlib-version>
  <short-name>x-c</short-name>
  <uri>http://dev.x.com/taglib/core/1.0</uri>
  <function>
    <description>Join elements of an Iterable into a string.</description>
    <display-name>Join</display-name>
    <name>join</name>
    <function-class>com.x.taglib.core.StringUtil</function-class>
    <function-signature>java.lang.String join(java.lang.Iterable, java.lang.CharSequence)</function-signature>
  </function>
</taglib>

While the TLD is a little verbose, knowing your way around one is a good skill for any developer working with JSP. And, since you've chosen a standard like JSP for presentation, there's a good chance you have tools that will help you out.

This approach has many advantages over the alternative of adding more methods to the underlying model. This function can be written once, and reused in any project. It works with a closed-source, third-party library. Different delimiters can be supported in different contexts, without polluting a model API with a new method for each.

Most importantly, it supports a separation of view and model-controller development roles. Tasks in these two areas are often performed by different people at different times. Maintaining a loose coupling between these layers minimizes complexity and maintenance costs. When even a trivial change like using a different delimiter in the presentation requires a programmer to modify a library, you have a very expensive and cumbersome system.

The StringUtil class is the same whether its exposed as a EL function or not. The only "extra" necessary is the TLD, which is trivial; a tool could easily generate it.

查看更多
放我归山
3楼-- · 2019-01-11 18:54

Could you use this? Seems like it wants an array instead of a list..

${fn:join(array, ";")}

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/join.fn.html

查看更多
不美不萌又怎样
4楼-- · 2019-01-11 18:54

Just put the string byside the var from server, like this:

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

         id="scheduled${conf.id}">

    ...
    </div>
</c:forEach>

Too late!!!

查看更多
萌系小妹纸
5楼-- · 2019-01-11 18:58

Figured out a somewhat dirty way to do this:

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

I just use <c:set> repeatedly, referencing it's own value, to append/concatenate the strings.

查看更多
▲ chillily
6楼-- · 2019-01-11 19:00

The way tag libraries are implemented seems to have moved on considerably since this answer was originally posted so I ended up making some drastic changes to get things working. My final result was:

Tag Library File:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>string_util</short-name>
  <uri>/WEB-INF/tlds/string_util</uri>
  <info>String Utilities</info>
  <tag>
    <name>join</name>
    <info>Join the contents of any iterable using a separator</info>
    <tag-class>XXX.taglib.JoinObjects</tag-class>
    <body-content>tagdependent</body-content>
    <attribute>
      <name>iterable</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.lang.Iterable</type>
    </attribute>
    <attribute>
      <name>separator</name>
      <required>false</required>
      <rtexprvalue>false</rtexprvalue>
      <type>java.lang.String</type>
    </attribute>
  </tag>

  <tag>
    <name>joinints</name>
    <info>Join the contents of an integer array using a separator</info>
    <tag-class>XXX.taglib.JoinInts</tag-class>
    <body-content>tagdependent</body-content>
    <attribute>
      <name>integers</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.lang.Integer[]</type>
    </attribute>
    <attribute>
      <name>separator</name>
      <required>false</required>
      <rtexprvalue>false</rtexprvalue>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</taglib>

JoinInts.java

public class JoinInts extends TagSupport {

    int[] integers;
    String separator = ",";

    @Override
    public int doStartTag() throws JspException {
        if (integers != null) {
            StringBuilder buf = new StringBuilder();
            if (separator == null) {
                separator = " ";
            }
            for (int i: integers) {
                if (buf.length() > 0) {
                    buf.append(separator);
                }
                buf.append(i);
            }
            try {
                pageContext.getOut().print(buf);
            } catch (IOException ex) {
                Logger.getLogger(JoinInts.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }

    public int[] getIntegers() {
        return integers;
    }

    public void setIntegers(int[] integers) {
        this.integers = integers;
    }

    public String getSeparator() {
        return separator;
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }
}

To use it:

<%@ taglib prefix="su" uri="/WEB-INF/tlds/string_util.tld" %>

[new Date(${row.key}), <su:joinints integers="${row.value}" separator="," />],
查看更多
Deceive 欺骗
7楼-- · 2019-01-11 19:04

If your sublist is an ArrayList and you do this:

<div class='scheduled' title="${conf.subject}: ${conf.invitees}" id="scheduled${conf.id}">

you obtain almost what you need.

The only difference is that the title will be: "Subject: [blah@blah.com, blah2@blah2.com, etc.]".

Maybe can be good enough for you.

查看更多
登录 后发表回答