Bantha Fodder
Bantha Fodder

Reputation: 1300

GWT Safe HTML Framework: When to use, and why?

In reading JavaDocs and various GWT articles, I've occassionally run into the following Safe* classes:

It looks like SafeHtml is somehow used when creating a new Widget or Composite, and helps ensure that the Widget/Composite doesn't execute any scripts on the client-side. Is this the case, or am I way off-base? Can someone provide a code example of SafeHtml being used properly in action?

If so, then what's the point of SafeHtmlBuilder? Do you use it inside of a Widget to somehow "build up" safe HTML?

Upvotes: 6

Views: 7143

Answers (2)

David Webb
David Webb

Reputation: 193716

The simplest way to view SafeHtml is as a String where any HTML markup has been appropriately escaped. This protects against Cross-Site Scripting (XSS) attacks as it ensures, for example, if someone enters their name in a form as <SCRIPT>alert('Fail')</SCRIPT> this is the text that gets displayed when your page is rendered rather than the JavaScript being run.

So instead of having something like:

String name = getValueOfName();
HTML widget = new HTML(name);

You should use:

String name = getValueOfName();
HTML widget = new HTML(SafeHtmlUtils.fromString(name));

SafeHtmlBuilder is like a StringBuilder except that it automatically escapes HTML markup in the Strings you add. So to extend the above example:

String name = getValueOfName();
SafeHtmlBuilder shb = new SafeHtmlBuilder();
shb.appendEscaped("Name: ").appendEscaped(name);
HTML widget = new HTML(shb.toSafeHtml());

The is a good guide to SafeHtml in the GWT documentation that is worth a read.

Upvotes: 9

Thomas Broyer
Thomas Broyer

Reputation: 64541

SafeHtmlBuilder is to SafeHtml what StringBuilder is to String.

As for the Safe* API, use it whenever you deal with HTML (or CSS for SafeStyles, or URLs for SafeUri and UriUtils), more precisely building HTML/CSS/URL from parts to be fed to the browser for parsing, with no exception.

Actually, we were recently discussing whether to deprecate Element.setInnerHtml and other similar APIs (HasHTML) in favor of Element.setInnerSafeHtml and the like (HasSafeHtml).

Upvotes: 8

Related Questions