【问题标题】:Can SafeHtmlBuilder excapse SafeHtml while still keeping SafeHtml the way it is(GWT)?SafeHtmlBuilder 能否在保持 SafeHtml 原样(GWT)的同时排除 SafeHtml?
【发布时间】:2013-12-21 02:26:34
【问题描述】:

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

例如,用户在文本框中输入:<h1>text <i>test</i></h1> 它会输出:

文本测试

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

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

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

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

文本测试

那么如何让这个字符串包含在标签内呢?

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

那么如何解决我的问题呢?

【问题讨论】:

    标签: gwt


    【解决方案1】:

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

    例子:

    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>");
    }
    

    【讨论】:

    • 我找到了一个更好的解决方案,将所有

      替换为“<h1>”然后追加

      然后清理,但这次我需要更改白名单标签以包含 h1。无论如何谢谢你

    猜你喜欢
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多