gpt4 book ai didi

spring - thymeleaf + Spring : How to keep line break?

转载 作者:IT老高 更新时间:2023-10-28 13:49:15 29 4
gpt4 key购买 nike

我正在使用带有 spring 的 Thymeleaf 模板引擎,我想显示通过多行文本区域存储的文本。

在我的数据库中,多行字符串与“\n”一起存储,如下所示:“Test1\nTest2\n....”

有了 th:text 我得到了:“Test1 Test2”,没有换行符。

如何使用 Thymeleaf 显示换行符并避免手动将 "\n"替换为 < br/>,然后避免使用 th:utext(此开放式 xss 注入(inject))?

谢谢!

最佳答案

你的两个选择:

  1. 使用 th:utext - 简单的设置选项,但更难阅读和内存
  2. 创建自定义处理器和方言 - 设置更复杂,但 future 使用更容易、更易读。

选项 1:

如果您使用表达式实用方法 #strings.escapeXml( text ) 转义文本,则可以使用 th:utext 以防止 XSS 注入(inject)和不需要的格式 - 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 编写了本教程)希望您可以将以下逻辑与他们的官方教程结合起来。也许有一天我会有一分钟的时间来完全更新它。但现在: Here's the official Thymeleaf tutorial for creating your own dialect.

设置完成后,您需要做的就是完成带有保留换行符的转义文本行输出:

<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 应用程序,您只需在 Template Engine 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.html , http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.htmlhttp://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html

关于spring - thymeleaf + Spring : How to keep line break?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30394419/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com