質問

Beanのリストがあり、各Beanにはそれ自体が電子メールアドレスのリストであるプロパティがあります。

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

これにより、リスト内のBeanごとに1つの<div>がレンダリングされます。

サブリストについて、リスト内の各エントリを連結して単一の文字列を形成し、title${conf.subject}属性の一部として表示できるようにしたい。どうして?これは、JavaScriptライブラリ(mootools)を使用してこの<=>をフローティングツールチップにし、ライブラリが<=>をツールチップのテキストに変換するためです。

したがって、<=>が<!> quot; Subject <!> quot;である場合、最終的に<=>の<=>を<!> quot; Subject:blah@blah.comにしたい、blah2 @ blah2.comなど<!> quot ;、サブリストのすべてのメールアドレスが含まれています。

JSP ELを使用してこれを行うにはどうすればよいですか?スクリプトレットブロックをjspファイルに入れないようにしています。

役に立ちましたか?

解決 2

これを行うためのやや汚い方法を見つけました:

<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>

<c:set>を繰り返し使用し、独自の値を参照して、文字列を追加/連結します。

他のヒント

<!> quot; clean <!> quot;これを行う方法は、関数を使用することです。 JSTL join関数はCollectionでは機能しないため、大きな問題なく独自のコードを記述し、大量のループコードをカットアンドペーストするのではなく、あちこちで再利用できます。

関数の実装と、Webアプリケーションにそれを見つける場所を知らせるTLDが必要です。これらをJARにまとめて、WEB-INF / libディレクトリにドロップします。

概要は次のとおりです。

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>

TLDは少し冗長ですが、JSPを使用する開発者にとっては、TLDを理解することは優れたスキルです。また、プレゼンテーション用にJSPのような標準を選択しているため、役立つツールがある可能性が高くなります。

このアプローチには、基礎となるモデルにメソッドを追加するという代替案に勝る多くの利点があります。この関数は一度作成すれば、どのプロジェクトでも再利用できます。クローズドソースのサードパーティライブラリで動作します。モデルAPIをそれぞれ新しいメソッドで汚染することなく、異なるコンテキストで異なる区切り文字をサポートできます。

最も重要なことは、ビューとモデルコントローラー開発の役割の分離をサポートしていることです。これらの2つの領域のタスクは、異なる時間に異なるユーザーによって実行されることがよくあります。これらの層間の疎結合を維持することにより、複雑さと保守コストが最小限に抑えられます。プレゼンテーションで別の区切り文字を使用するような些細な変更でも、プログラマがライブラリを変更する必要がある場合、非常に高価で扱いにくいシステムになります。

StringUtilクラスは、EL関数として公開されているかどうかにかかわらず同じです。唯一の<!> quot; extra <!> quot;簡単なTLDが必要です。ツールで簡単に生成できます。

これを使用できますか?リストではなく配列が必要なようです。

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

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

サブリストがArrayListであり、これを行う場合:

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

必要なものはほとんど入手できます。

唯一の違いは、タイトルが次のようになることです。 <!> quot; Subject:[blah @ blah.com、blah2 @ blah2.comなど] <!> quot;。

多分あなたにとっては十分かもしれません。

これはあなたが望むものだと思います:

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

この場合、タブID(キー)とURL(値)のハッシュマップがありました。 tabAttrs変数は、これより前には設定されていません。そのため、値をtabAttrsの現在の値(開始するには '')にキー/値式を加えたものに設定します。

次のように、サーバーからの変数の横に文字列を置くだけです:

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

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

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

遅すぎる!!!

この回答が最初に投稿されて以来、タグライブラリの実装方法はかなり進んでいるようです。最終結果は次のとおりです。

タグライブラリファイル:

<?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;
    }
}

使用するには:

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

[new Date(${row.key}), <su:joinints integers="${row.value}" separator="," />],

EL 3.0ストリームAPIを使用できます。たとえば、文字列のリストがある場合、

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

exのオブジェクトのリストがある場合。 Person(firstName、lastName)を使用し、それらのプロパティを1つだけ連結したい場合(exfirstName)、mapを使用できます。

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

あなたの場合、そのようなものを使用することができます(最後の「、」も削除します)、

<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>

注意! EL 3.0 Stream API は、 Java 8 Stream APIであり、それとは異なります。後方互換性を壊すため、両方のAPIをsuncすることはできません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top