outputText中除换行符外的所有内容

outputText中除换行符外的所有内容

本文介绍了转义h:outputText中除换行符外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户在文本区域中输入的文本,我想在另一页上显示它.

I have text that the user input in a textarea and I want to display it on a another page.

第一个问题是来自textarea的换行符是\ r \ n而不是br,但是我可以简单地替换所有换行符.我需要帮助的实际问题是在此之后显示它:

The first issue is that the linebreaks coming from the textarea are \r\n instead of br, but I could simply just replace all of them. The actual problem I need help with is displaying it after that:

h:outputText默认情况下会转义所有内容,因此要使换行符正常工作,我需要执行escape ="false",但是出于明显的原因,我不希望用户通过输入其他内容来弄乱页面HTML标记,或更糟糕的是Javascript.因此,我需要以某种方式摆脱除换行符以外的所有内容.

h:outputText by default escapes everything, so to get the linebreaks to work I need to do escape="false", but for obvious reasons I don't want the user to be able to mess up the page by inputting other HTML tags or even worse, Javascript. So I need to somehow escape everything but the linebreaks.

我应该怎么做?还是可能有一个不同的JSF组件可以使这一过程变得更简单?

How should I do this? Or is there maybe a different JSF component that would make this more simple?

不幸的是,不能使用前置标签或CSS空格.

Unfortunately pre tags or CSS white-space are not an option.

推荐答案

除了将\n替换为<br>并使用<h:outputText escape="false">,您还可以只显示经过预格式化的文本,以使\n看起来像是真正的新队.您可以使用元素的 CSS white-space属性将此属性设置为prepre-wrappre-line.

Instead of replacing \n by <br> and using <h:outputText escape="false">, you can also just display the text preformatted so that \n appears as a true newline. You can use the element's CSS white-space property for this which can be set to pre, pre-wrap or pre-line.

例如

<h:outputText value="#{bean.text}" styleClass="preformatted" />

使用

.preformatted {
    white-space: pre;
}

如果您真的打算将文本显示为未转义的HTML,则可以使用能够胜任工作的HTML解析器(例如Jsoup)来清除XSS攻击向量.另请参阅我昨天发布的以下答案:具有html样式的JSF OutputText

If you really intend to present the text as unescaped HTML, then you can sanitize XSS attack vectors away by using a HTML parser capable of the job, such as Jsoup. See also this answer which I posted yesterday: JSF OutputText with html style.

这篇关于转义h:outputText中除换行符外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:16