SafeHtmlBuilder能否在保持SafeHtml(GWT)的同时实现SafeHtml?

时间:2013-12-21 02:26:34

标签: gwt

这是我的要求。我有一个文本框和用户可以在文本框中键入任何内容,系统会将其转换为html。但是,它只会转换<b> or <i>代码&amp;忽略所有其他标签。该文本的结果将放入<h1>标记。

例如,文本框中的用户类型:<h1>text <i>test</i></h1>它将输出:

&lt; h1&gt; text test &lt; / h1&gt;

因此,如果用户在文本框中键入<h1>,那么系统应该足够聪明,知道它应该逃脱<h1>但是必须将<h1>放到最后的字符串中

代码可能是这样的。我使用SimpleHtmlSanitizer来清理字符串&amp;只允许<b> or <i>

SafeHtml mySafeHtml=MySimpleHtmlSanitizer.sanitizeHtml("<h1>text <i>test</i></h1>");

所以,如果我打印出mySafeHtml,那么它将显示如下:

&lt; h1&gt; text test &lt; / h1&gt;

但是如何让String包含在标签内?

SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<h1>");
builder.appendEscaped(mySafeHtml); // err here cos SafeHtmlBuilder does not excapse SafeHtml?
builder.appendHtmlConstant("</h1>");

那么如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

我对此的看法是这样的,为什么不检查您的mySafeHtml是否以<h1>开头,然后有条件地附加?

示例:

SafeHtmlBuilder builder = new SafeHtmlBuilder();

//check if your `mySafeHtml` starts and ends with <h1>

if(  (mySafeHtml.startsWith("<h1>") 
       || mySafeHtml.startsWith("<H1>"))
  && (mySafeHtml.endsWith("</h1>")
      || mySafeHtml.endsWith("</H1>"))
  )
{
    builder.appendEscaped(mySafeHtml); // err here cos SafeHtmlBuilder does not excapse 
}
else
{
   builder.appendHtmlConstant("<h1>");
   builder.appendEscaped(mySafeHtml); // err here cos SafeHtmlBuilder does not excapse  SafeHtml?
   builder.appendHtmlConstant("</h1>");
}
相关问题