I'm currently getting to grips with Groovy and Grails. One major frustration that took a while to figure out was HTML escaping in GSP pages. Here's the simple lowdown, including at the end the important bit that I had struggled to realise, which is how to not escape specific strings when global HTML escaping is turned on.

Manual escaping

Out of the box (i.e. with a vanilla Grails app with default config) you need to explicitly escape any dangerous strings with the encodeAsHTML() function that Grails makes available on all Strings: ${dangerString.encodeAsHTML()}. This is a bit verbose, but at least it's very clear, and because it's just a method on String it's available everywhere in your app, not just in GSPs.

Auto-escaping with default codec

If you modify Config.groovy to contain grails.views.default.codec = "html" (which is there by default and set to "none") then it automatically calls encodeAsHTML() for you whenever you use ${} in GSPs. This is clearly quite a handy option and a much safer way of configuring things as it lessens the likelihood of slipping up and leaving a hole in your app.

Overriding auto-escaping per item

So far this is all exactly as per the Grails docs (which go into much more detail on codecs and what's really going on, including creating your own) but the crucial bit they fail to mention is what to do if you've turned on the global html codec, but have situations where you don't want escaping. The answer is to simply use the alternative JSP style interpolation syntax <%=mySafeHTMLString%> since the codec is only applied to ${}.

Overriding auto-escaping per page

You can also set the codec on a per-page basis, overriding that set in Config.groovy, with <%@page defaultCodec="html" %> or <%@page defaultCodec="none" %> as appropriate.


  1. David Castro

    Thanks for the tip. Gotta be wary of those user inputs….

  2. thanks, it was helpful

  3. You just cured me of a headache I’ve been having for hours. Thank you for such a succinct and thorough answer.

  4. thanks, it was very helpful
    Other way to do it on field basis :-
    You can use g:fieldValue tag

  5. Many thanks to you, I was starting to think about retiring myself in some asylum…

  6. fieldvalue really is only useful with GORM. If you have inputs from files or API’sor other sources you are trying to use, this isn’t very useful.

Leave a Reply

Your email address will not be published. Required fields are marked *