In reading JavaDocs and various GWT articles, I've occassionally run into the following Safe*
classes:
SafeHtml
SafeHtmlBuilder
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?
A SafeHtml is a string-like object that carries the security type contract that its value as a string will not cause untrusted script execution when evaluated as HTML in a browser.
It is used essentially like a StringBuilder ; unlike a StringBuilder , it automatically HTML-escapes appended input where necessary. In addition, it supports methods that allow strings with HTML markup to be appended without escaping: One can append other SafeHtml objects, and one can append constant strings.
An object that implements this interface encapsulates HTML that is guaranteed to be safe to use (with respect to potential Cross-Site-Scripting vulnerabilities) in an HTML context. Note on usage: SafeHtml should be used to ensure user input is not executed in the browser.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With