{"id":8539,"date":"2012-09-25T02:49:09","date_gmt":"2012-09-24T21:19:09","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=8539"},"modified":"2012-09-25T02:49:09","modified_gmt":"2012-09-24T21:19:09","slug":"enhance-httpservletrequest-using-metaprogramming","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/enhance-httpservletrequest-using-metaprogramming\/","title":{"rendered":"Enhance HttpServletRequest using metaprogramming"},"content":{"rendered":"<p style='padding-bottom:10px;'>Most of the times we use <code>request.getHeader(\"user-agent\")<\/code> to get the client browser user-agent details inside the Grails Filters or Controllers. User-agent is one of the examples. There are so many such methods e.g. method for checking whether the request was an ajax call, getting IP address of the client machine, checking whether the request is made by a mobile browser etc. Lets create a class with a static method (create file in<code> grails-app\/src<\/code> source folder) :\n<\/p>\n<p>[groovy]<br \/>\nimport javax.servlet.http.HttpServletRequest<\/p>\n<p>class HttpRequestMetaClassEnhancer{<br \/>\n  public static void enhanceRequest(){<br \/>\n    HttpServletRequest.metaClass {<br \/>\n       getRemoteIPAddress = {<br \/>\n           delegate.getHeader(&quot;x-forwarded-for&quot;) ?: delegate.remoteAddr<br \/>\n       }<br \/>\n       isAjax = {<br \/>\n           delegate.getHeader(&quot;X-Requested-With&quot;) == &quot;XMLHttpRequest&quot;<br \/>\n       }<br \/>\n       getSiteUrl = {<br \/>\n           delegate.scheme + &quot;:\/\/&quot; + delegate.serverName + &quot;:&quot; + delegate.serverPort + delegate.getContextPath()<br \/>\n       }<br \/>\n       getUserAgent = {<br \/>\n           delegate.getHeader(&quot;User-Agent&quot;)<br \/>\n       }<br \/>\n       isMobileBrowser = {<br \/>\n\t   delegate.getHeader(&quot;User-Agent&quot;).matches(&quot;(?i).*(android|iphone|ipad).*&quot;)<br \/>\n\t}<br \/>\n          \/*<br \/>\n              Keep adding methods that are common to projects as comment to blog.<br \/>\n              I will update this blog with your helper methods<br \/>\n           *\/<br \/>\n     }<br \/>\n  }<br \/>\n}<br \/>\n[\/groovy]<\/p>\n<p style='padding-bottom:10px;'>\nIn most of the projects, we use an <em>inline plugin<\/em> which adds our commonly used utility methods to respective groovy classes using groovy metaprogramming. <code>Bootstrap.groovy<\/code> is another place for adding dynamic behaviour to classes like <code>HttpServletRequest<\/code> so that it is ready before being used inside <em>Grails Controllers\/Filters <\/em>etc. Just make a call to <code>enahceRequest<\/code> static method of <code>HttpRequestMetaClassEnhancer<\/code> class in init closure of <code>Bootstrap.groovy<\/code> file.\n<\/p>\n<p>[groovy]<br \/>\nclass Bootstrap{<br \/>\n    def init = { servletContext -&gt;<br \/>\n\tHttpRequestMetaClassEnhancer.enahceRequest()<br \/>\n \t}<br \/>\n    def destroy = {}<br \/>\n}<\/p>\n<p>[\/groovy]<\/p>\n<p style='padding-bottom:10px;'>\nNow you can access properties like <code>remoteIPAddress<\/code>, <code>ajax<\/code>, <code>siteUrl<\/code>, <code>userAgent<\/code>, <code>mobileBrowser<\/code> etc. on request object in Grails Filters\/Controllers. See below a sample filter which prints request related information on each request received to the server log.\n<\/p>\n<p>[groovy]<br \/>\nclass ApplicationFilters{<br \/>\ndef filters = {<br \/>\n        logParams(controller: &#8216;*&#8217;, action: &#8216;*&#8217;) {<br \/>\n            before = {<br \/>\n                log.info &quot;[IP: ${request.remoteIPAddress},&quot;+<br \/>\n                           &quot;url: ${params.controller}\/${params.action},&quot;+<br \/>\n                           &quot;ajax: ${request.ajax},&quot;+<br \/>\n                           &quot;Mobile browser: ${request.mobileBrowser} ]:&quot;+<br \/>\n                            params.findAll {![&#8216;password&#8217;, &#8216;passwd&#8217;, &#8216;controller&#8217;, &#8216;action&#8217;].contains(it.key)}<br \/>\n           }<br \/>\n      }<br \/>\n}<\/p>\n<p>[\/groovy]<\/p>\n<p>Or a sample controller : <\/p>\n<p>[groovy]<br \/>\nclass UtilController{<br \/>\n  def index(){<br \/>\n      if(request.mobileBrowser){<br \/>\n          render &quot;You got a nice mobile. You are viewing : &quot;+request.siteUrl<br \/>\n      }else{<br \/>\n           request.ajax ? render(view:&#8217;index) : render(template :&#8217;tabularData&#8217;)<br \/>\n      }<br \/>\n  }<br \/>\n}<br \/>\n[\/groovy]<\/p>\n<p style='padding-bottom:10px;'>\nThanks to all the contributors whose helper methods has made this a long blog.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Blog teach you : how to enhance http request object by adding helper methods using groovy meta programming. The blog contains most commonly methods to request object such as isAjax, siteUrl, isMobileBrowser, remoteIPAddress etc. Once they are injected from Bootstrap.groovy init closure, the new methods are available in controllers and filters. Blog shows some use cases where these helper methods has been used successfully.<\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":2},"categories":[7],"tags":[1068,4840,1062,9,1061,1063,1066,145,1064,1065,1067],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/8539"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=8539"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/8539\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=8539"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=8539"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=8539"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}