Cool way to get/set processed HTML Markup in filters

27 / Sep / 2012 by Kushal Likhi 1 comments

Hi,

 

There was a case where i had to encrypt the HTML output of the GSP before displaying it to user. There are a lot of ways to do it, but i wanted to make is as simple as possible. Hence here is the pattern i used:

 

Note: This is just an example, you can use this concept to do thousands of cool things, like: pdf export etc..

 

ON THE GSP

<html>
<head>
<meta name="encrypt" value="true" />   
    ...
</head>
 .... misc code
</html>

Here what is did is, i created a GSP and just added a meta property to it saying “encrypt true”.

 

Now here is the Code for the Grails Filters (See inline comments)

def filters = {
        all(controller: '*', action: '*') {
            before = {                
            }
            after = { Map model ->
                try {
                    //Get the Site Mesh Page Instance
                    GSPSitemeshPage sitemeshPage = response?.getContent() as GSPSitemeshPage
                   
                    //Check if it is actual sitemest page, not just plain rendered content
                    if (sitemeshPage && sitemeshPage.getPage()) {
                        //Get the meta property value.
                        String metaPropValue = sitemeshPage.getProperty("meta.encrypt")
                        if (metaPropValue && metaPropValue == "true") {
                            //This is how you can get html contents of head/body after all tags resolved.
                            String head = new String(sitemeshPage.getHead())
                            String body = new String(sitemeshPage.getBody())

                            //Buffer for new body
                            StreamCharBuffer writer = new StreamCharBuffer()
                            //Write to buffer new content
                            writer.getWriter().write(encryptionService.encrypt(body))
                            sitemeshPage.setBodyBuffer(writer)
                        }
                    }
                } catch (Throwable ex) {
                    ex.printStackTrace()
                }
            }
            afterView = { Exception e ->

            }
        }
    }

 

And hence we have this processed content in response :)

 

 

Regards
Kushal Likhi

FOUND THIS USEFUL? SHARE IT

comments (1 “Cool way to get/set processed HTML Markup in filters”)

  1. Jason John

    Great Article!
    Just for record, this is intelligrape stuff we readers look for, great tips which we can’t find anywhere else.

    I will try the pdf export with this, and let you know. Seems promising though.

    Reply

Leave a comment -