복붙노트

[SPRING] Thymeleaf + Spring : 줄 바꿈을 유지하는 방법?

SPRING

Thymeleaf + Spring : 줄 바꿈을 유지하는 방법?

저는 Spring에서 Thymeleaf 템플릿 엔진을 사용 중이며 여러 줄 문자 영역을 통해 저장된 텍스트를 표시하고 싶습니다.

내 데이터베이스에서 다중 행 문자열은 "\ n"과 같이 저장됩니다 : "Test1 \ nTest2 \ n ...."

th : ​​텍스트 : 줄 바꿈없이 "Test1 Test2"가 있습니다.

Thymeleaf를 사용하여 줄 바꿈을 표시하고 수동으로 "\ n"을
로 바꾸지 않고 th : utext (xss 삽입에이 열린 양식)를 사용하지 마십시오.

감사 !

해결법

  1. ==============================

    1.두 가지 옵션 :

    두 가지 옵션 :

    옵션 1:

    expression 유틸리티 메소드 # strings.escapeXml (텍스트)를 사용하여 텍스트를 이스케이프하면 XSS 주입 및 원하지 않는 서식을 방지하기 위해 th : utext를 사용할 수 있습니다. http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html # 문자열

    이 플랫폼을 독립적으로 만들려면 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;
        }
    
    
    }
    

    이제 프로세서를 추가 했으므로 프로세서를 추가 할 사용자 지정 dialect가 필요합니다.

    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 애플리케이션을 작성하고 있다면 Template Engine 빈의 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를 사용하려는 경우 관리 패키지로 dialect가 포함 된 기본 패키지에 @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.html, http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html 및 http : //www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html

  2. ==============================

    2.내 경우 escapeJava ()는 키릴 기호에 대한 유니 코드 값을 반환하므로 unescapeJava () 메서드 도움말을 모두 랩핑하여 문제를 해결합니다.

    내 경우 escapeJava ()는 키릴 기호에 대한 유니 코드 값을 반환하므로 unescapeJava () 메서드 도움말을 모두 랩핑하여 문제를 해결합니다.

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

    3.어쩌면 OP가 염두에 두었던 것이 아닐지 모르지만 이것은 작동하고 코드 삽입을 방지합니다.

    어쩌면 OP가 염두에 두었던 것이 아닐지 모르지만 이것은 작동하고 코드 삽입을 방지합니다.

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

    (HTML5 스타일의 Thymeleaf 사용.)

  4. ==============================

    4.이 시도

    이 시도

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

    5.th : ​​utext를 사용하고 문자열에 줄 바꿈을 추가해야합니다. 내 코드는 다음과 같습니다.

    th : ​​utext를 사용하고 문자열에 줄 바꿈을 추가해야합니다. 내 코드는 다음과 같습니다.

    StringBuilder message = new StringBuilder();
            message.append("some text");
            message.append("<br>");
            message.append("some text");
    
    <span th:utext="${message}"></span>
    
  6. ==============================

    6.thymeleaf에서 jQuery를 사용하는 경우 다음을 사용하여 코드의 서식을 지정할 수 있습니다.

    thymeleaf에서 jQuery를 사용하는 경우 다음을 사용하여 코드의 서식을 지정할 수 있습니다.

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

    그 대답이 당신을 도울 수 있기를 바랍니다.

  7. from https://stackoverflow.com/questions/30394419/thymeleaf-spring-how-to-keep-line-break by cc-by-sa and MIT license