web-dev-qa-db-ja.com

Thymeleaf + Spring:改行を維持する方法は?

私はThymeleafテンプレートエンジンを春で使用していますが、複数行のテキストエリアに保存されているテキストを表示したいと思います。

私のデータベースでは、複数行の文字列は「Test1\nTest2\n ....」のように「\ n」で保存されています

Th:textを使用すると、改行なしの「Test1 Test2」が得られます。

Thymeleafを使用して改行を表示し、手動で「\ n」を<br />に置き換えてからth:utext(xssインジェクションへのこのオープンフォーム)を使用しないようにする方法

ありがとう!

21
Daividh

2つのオプション:

  1. Th:utextを使用する-セットアップオプションは簡単ですが、読みやすく覚えにくい
  2. カスタムプロセッサとダイアレクトを作成します-より複雑なセットアップですが、より簡単で読みやすい将来の使用。

オプション1:

式ユーティリティメソッド#strings.escapeXml( text )を使用してテキストをエスケープし、XSSインジェクションと不要なフォーマットを防ぐ場合は、th:utextを使用できます- http://www.thymeleaf.org/doc/tutorials/2.1 /usingthymeleaf.html#strings

このプラットフォームを独立させるには、T(Java.lang.System).getProperty('line.separator')を使用して行区切り文字を取得します。

既存のThymeleaf式ユーティリティを使用すると、これは機能します。

<p th:utext="${#strings.replace( #strings.escapeXml( text ),T(Java.lang.System).getProperty('line.separator'),'&lt;br /&gt;')}" ></p>

オプション2:

このためのAPIは3で異なります(このチュートリアルを2.1向けに作成しました)以下のロジックを公式チュートリアルと組み合わせることができれば幸いです。いつか、これを完全に更新する時間があります。しかし、今のところ: 独自の方言を作成するための公式Thymeleafチュートリアルです。

セットアップが完了したら、改行を保持してエスケープされたテキスト行出力を実行するために必要な作業はすべて次のとおりです。

<p fd:lstext="${ text }"></p>

作業を行う主な部分はプロセッサです。次のコードでトリックを行います:

package com.foo.bar.thymeleaf.processors 

import Java.util.Collections;
import Java.util.List;

import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.attr.AbstractChildrenModifierAttrProcessor;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.unbescape.html.HtmlEscape;

public class HtmlEscapedWithLineSeparatorsProcessor extends
        AbstractChildrenModifierAttrProcessor{

    public HtmlEscapedWithLineSeparatorsProcessor(){
        //only executes this processor for the attribute 'lstext'
        super("lstext");
    }

    protected String getText( final Arguments arguments, final Element element,
            final String attributeName) {

        final Configuration configuration = arguments.getConfiguration();

        final IStandardExpressionParser parser =
            StandardExpressions.getExpressionParser(configuration);

        final String attributeValue = element.getAttributeValue(attributeName);

        final IStandardExpression expression =
            parser.parseExpression(configuration, arguments, attributeValue);

        final String value = (String) expression.execute(configuration, arguments);

        //return the escaped text with the line separator replaced with <br />
        return HtmlEscape.escapeHtml4Xml( value ).replace( System.getProperty("line.separator"), "<br />" );


    }



    @Override
    protected final List<Node> getModifiedChildren(
            final Arguments arguments, final Element element, final String attributeName) {

        final String text = getText(arguments, element, attributeName);
        //Create new text node signifying that content is already escaped.
        final Text newNode = new Text(text == null? "" : text, null, null, true);
        // Setting this allows avoiding text inliners processing already generated text,
        // which in turn avoids code injection.
        newNode.setProcessable( false );

        return Collections.singletonList((Node)newNode);


    }

    @Override
    public int getPrecedence() {
        // A value of 10000 is higher than any attribute in the SpringStandard dialect. So this attribute will execute after all other attributes from that dialect, if in the same tag.
        return 11400;
    }


}

プロセッサができたので、プロセッサを追加するためのカスタム方言が必要です。

package com.foo.bar.thymeleaf.dialects;

import Java.util.HashSet;
import Java.util.Set;

import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;

import com.foo.bar.thymeleaf.processors.HtmlEscapedWithLineSeparatorsProcessor;

public class FooDialect extends AbstractDialect{

    public FooDialect(){
        super();
    }

    //This is what all the dialect's attributes/tags will start with. So like.. fd:lstext="Hi David!<br />This is so much easier..."
    public String getPrefix(){
        return "fd";
    }

    //The processors.
    @Override
    public Set<IProcessor> getProcessors(){
        final Set<IProcessor> processors = new HashSet<IProcessor>();
        processors.add( new HtmlEscapedWithLineSeparatorsProcessor() );
        return processors;
    }

}

次に、xmlまたはJava構成に追加する必要があります。

Spring MVCアプリケーションを作成する場合は、テンプレートエンジンBeanのadditionalDialectsプロパティで設定するだけで、デフォルトのSpringStandardダイアレクトに追加されます。

    <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
  <property name="templateResolver" ref="templateResolver" />
  <property name="additionalDialects">
    <set>
      <bean class="com.foo.bar.thymeleaf.dialects.FooDialect"/>
    </set>
  </property>
    </bean>

または、Springを使用していて、JavaConfigを使用する場合は、マネージドBeanとして方言を含むベースパッケージで@Configurationアノテーションが付けられたクラスを作成できます。

package com.foo.bar;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.foo.bar.thymeleaf.dialects.FooDialect;

@Configuration
public class TemplatingConfig {

    @Bean
    public FooDialect fooDialect(){
        return new FooDialect();
    }
}

カスタムプロセッサとダイアレクトの作成に関する詳細なリファレンスを以下に示します。 http://www.thymeleaf.org/doc/articles/sayhelloextendingthymeleaf5minutes.htmlhttp://www.thymeleaf.org /doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html および http://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html

22
David Roberts

OPが意図したものではないかもしれませんが、これは機能し、コードインジェクションを防ぎます。

<p data-th-utext="${#strings.replace(#strings.escapeXml(text),'&#10;','&lt;br&gt;')}"></p>

(HTML5スタイルのThymeleafを使用。)

6
holmis83

私の場合、escapeJava()はキリル文字のUnicode値を返すため、すべてをunescapeJava()メソッドでラップして問題を解決します。

<div class="text" th:utext="${#strings.unescapeJava(#strings.replace(#strings.escapeJava(comment.text),'\n','&lt;br /&gt;'))}"></div>
5

これを試して

<p th:utext="${#strings.replace(#strings.escapeJava(description),'\n','&lt;br /&gt;')}" ></p>

ThymeleafでjQueryを使用している場合、これを使用してコードをフォーマットできます。

$('#idyourdiv').val().replace(/\n\r?/g, '<br />')

答えがあなたを助けることを願っています

0
HAJARI Youssef

Th:utextを使用して、文字列に改行を追加する必要があります。私のコードは:

StringBuilder message = new StringBuilder();
        message.append("some text");
        message.append("<br>");
        message.append("some text");

<span th:utext="${message}"></span>
0