Thymeleaf + Spring:如何保持换行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30394419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thymeleaf + Spring : How to keep line break?
提问by Daividh
I'm using Thymeleaf template engine with spring and I'd like to display text stored throught a multiline textarea.
我正在使用带有 spring 的 Thymeleaf 模板引擎,我想显示通过多行文本区域存储的文本。
In my database multiline string are store with "\n" like this : "Test1\nTest2\n...."
在我的数据库中,多行字符串以“\n”存储,如下所示:“Test1\nTest2\n....”
With th:text i've got : "Test1 Test2" with no line break.
使用 th:text 我得到:“Test1 Test2”,没有换行符。
How I can display line break using Thymeleaf and avoid manually "\n" replacing with < br/> and then avoid using th:utext (this open form to xss injection) ?
我如何使用 Thymeleaf 显示换行符并避免手动将“\n”替换为 < br/> 然后避免使用 th:utext (这种开放形式到 xss 注入)?
Thanks !
谢谢 !
回答by David Roberts
Two of your options:
您的两个选择:
- Use th:utext - easy setup option, but harder to read and remember
- Create a custom processor and dialect - more involved setup, but easier, more readable future use.
- 使用 th:utext - 简单的设置选项,但更难阅读和记忆
- 创建自定义处理器和方言 - 更复杂的设置,但更容易,更易读的未来使用。
Option 1:
选项1:
You can use th:utext if you escape the text using the expression utility method #strings.escapeXml( text )
to prevent XSS injection and unwanted formatting - http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings
如果使用表达式实用程序方法#strings.escapeXml( text )
对文本进行转义以防止 XSS 注入和不需要的格式,则可以使用 th:utext - http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings
To make this platform independent, you can use T(java.lang.System).getProperty('line.separator')
to grab the line separator.
为了使这个平台独立,您可以使用T(java.lang.System).getProperty('line.separator')
抓取行分隔符。
Using the existing Thymeleaf expression utilities, this works:
使用现有的 Thymeleaf 表达式实用程序,这有效:
<p th:utext="${#strings.replace( #strings.escapeXml( text ),T(java.lang.System).getProperty('line.separator'),'<br />')}" ></p>
Option 2:
选项 2:
The API for this is now different in 3 (I wrote this tutorial for 2.1)Hopefully you can combine the below logic with their official tutorial. One day maybe I'll have a minute to update this completely. But for now: Here's the official Thymeleaf tutorial for creating your own dialect.
用于此的 API 现在在 3 中有所不同(我为 2.1 编写了本教程)希望您可以将以下逻辑与他们的官方教程结合起来。有一天,也许我会有一分钟的时间来完全更新它。但是现在: 这是用于创建您自己的方言的官方 Thymeleaf 教程。
Once setup is complete, all you will need to do to accomplish escaped textline output with preserved line breaks:
设置完成后,您需要做的就是完成带有保留换行符的转义文本行输出:
<p fd:lstext="${ text }"></p>
The main piece doing the work is the processor. The following code will do the trick:
完成这项工作的主要部分是处理器。以下代码可以解决问题:
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;
}
}
Now that you have the processor, you need a custom dialect to add the processor to.
现在您有了处理器,您需要一个自定义方言来添加处理器。
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;
}
}
Now you need to add it to your xml or java configuration:
现在您需要将其添加到您的 xml 或 java 配置中:
If you are writing a Spring MVC application, you just have to set it at the additionalDialects property of the Template Engine bean, so that it is added to the default SpringStandard dialect:
如果您正在编写 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>
Or if you are using Spring and would rather use JavaConfig you can create a class annotated with @Configuration in your base package that contains the dialect as a managed 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();
}
}
Here are some further references on creating custom processors and dialects: http://www.thymeleaf.org/doc/articles/sayhelloextendingthymeleaf5minutes.html, http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.htmland http://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html
以下是有关创建自定义处理器和方言的一些进一步参考: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
回答by holmis83
Maybe not what the OP had in mind, but this works and prevents code injection:
也许不是 OP 的想法,但这有效并防止代码注入:
<p data-th-utext="${#strings.replace(#strings.escapeXml(text),' ','<br>')}"></p>
(Using HTML5-style Thymeleaf.)
(使用 HTML5 风格的 Thymeleaf。)
回答by Evgeniy Vynogradov
In my case escapeJava()
returns unicode values for cyrillic symbols, so I wrap all in unescapeJava()
method help to solve my problem.
在我的情况下,escapeJava()
返回西里尔符号的 unicode 值,因此我将所有内容包装在unescapeJava()
方法帮助中以解决我的问题。
<div class="text" th:utext="${#strings.unescapeJava(#strings.replace(#strings.escapeJava(comment.text),'\n','<br />'))}"></div>
回答by HAJARI Youssef
If you are using jQuery in thymleaf, you can format your code using this:
如果您在 thymleaf 中使用 jQuery,则可以使用以下格式设置代码格式:
$('#idyourdiv').val().replace(/\n\r?/g, '<br />')
Hope that answer can help you
希望答案能帮到你
回答by Stefan Doskovi?
You need to use th:utext and append break line to string. My code is:
您需要使用 th:utext 并将换行符附加到字符串。我的代码是:
StringBuilder message = new StringBuilder();
message.append("some text");
message.append("<br>");
message.append("some text");
<span th:utext="${message}"></span>
回答by K. Siva Prasad Reddy
Try this
尝试这个
<p th:utext="${#strings.replace(#strings.escapeJava(description),'\n','<br />')}" ></p>