24 August, 2011

Power of HtmlUtil

Many time we know that we need to escape the URL title and need mechanisms in Liferay to escape characters.
So here is the brief of escaping :

Functions :

  • HtmlUtil.escape() is for inserting untrusted data into an HTML element
  • HtmlUtil.escapeHREF() is for inserting full URLs into the href attribute
  • HtmlUtil.escapeURL() is for inserting untrusted data into URL parameter values
  • HtmlUtil.escapeAttribute() is for inserting untrusted data into HTML element attribute values
  • HtmlUtil.escapeCSS() is for inserting untrusted data into CSS property values
  • HtmlUtil.escapeJS() is for inserting untrusted data into JavaScript strings

When to Escape ???

Escaping at the right time is important to make sure that 1) data is not escaped multiple times and 2) data is not changed to a different value before all business logic is done processing.

Rule 1 : Don't escape before persisting 

There's a few reason why it's generally a bad idea to escape the data before it's persisted.
  1. It increases the size of the data that must be stored
  2. You may need the original at some point in the future. If the data is escaped already, it'll be very difficult to get back the original.

Rule 2 : Escape at the last minute 

Escaping should be done at the last minute. This avoids situations where the data is escaped before all the business logic is done. Practically, this means that most of the escaping should be done in .jsp files and not in .java files.

Pattern 1 : LanguageUtil 

The values in a Language.properties file may contain HTML elements and they are always safe. So, you should avoid
HtmlUtil.escape(LanguageUtil.format(pageContext, "entries-with-tag-x", tagName))
and instead do
LanguageUtil.format(pageContext, "entries-with-tag-x", HtmlUtil.escape(tagName))

Rate Me:

Liferay 7.3 compatibility matrix

Compatibility Matrix Liferay's general policy is to test Liferay Portal CE against newer major releases of operating systems, open s...