{"id":23997,"date":"2015-07-27T19:35:24","date_gmt":"2015-07-27T14:05:24","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=23997"},"modified":"2015-07-29T10:28:14","modified_gmt":"2015-07-29T04:58:14","slug":"grails-filter-at-top-of-filter-invocation-chain","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/grails-filter-at-top-of-filter-invocation-chain\/","title":{"rendered":"Grails Filter at top of Filter Invocation Chain"},"content":{"rendered":"<p style=\"text-align: left;\">Sometimes in a web application we need filtering on request to a resource or on response, or on both. In <a title=\"Grails Devlopment\" href=\"http:\/\/www.tothenew.com\/grails-application-development\">Grails<\/a>, it could be done easily via creating a filter. Just run <code>grails create-filters [filter-name]<\/code> and it will generate a filter in the application. To run a filter before all other filters, just put that filter at top of other filters in the class. If we have multiple filter classes defined then we can use <code>dependsOn<\/code> to specify that this filter depends upon other filters and they should be executed first.<\/p>\n<p>[code lang=&#8221;groovy&#8221;]<br \/>\nclass MyFilters{<br \/>\ndef dependsOn=[HighPriorityFilters]<br \/>\n    def filters= {<br \/>\n        doSomething(uri:&quot;\/*&quot;){<br \/>\n        \/\/logic<br \/>\n        }<br \/>\n    }<br \/>\n}<\/p>\n<p>class HighPriorityFilters{<br \/>\n    def filters={<br \/>\n        doSomething(uri:&quot;\/*&quot;){<br \/>\n        \/\/logic<br \/>\n        }<br \/>\n    }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p>But this is only helpful only if application is not using any other plugins which use their own filters. To overcome this problem we would have to use Java EE filters along with some tweaks to web.xml.<\/p>\n<p><span style=\"text-decoration: underline;\">Creating a Filter<\/span>: Create a new groovy\/java class under src directory in your application. Implement <code>javax.servlet.Filter<\/code> interface. Write your logic in doFilter() method.<\/p>\n<p><span style=\"text-decoration: underline;\">Put it on top of Filter Chain<\/span>: Java&#8217;s Filter order is defined in web.xml. To execute our newely created filter before all other filters we have two approaches:<\/p>\n<h3 style=\"text-align: left;\">1. <span style=\"text-decoration: underline;\">Edit web.xml manually<\/span><\/h3>\n<p style=\"text-align: left;\">To modify web.xml, first we need to download the scaffolding templates using <code>grails install-templates<\/code>. This command will download templates being used by Grails to generate different artifacts. We can find the web.xml template under <code>src\/templates\/war\/web.xml<\/code>. If you will look into the web.xml file you will find filter mappings entries like this:<\/p>\n<p>[code lang=&#8221;xml&#8221;]<br \/>\n\t&lt;filter-mapping&gt;<br \/>\n        &lt;filter-name&gt;charEncodingFilter&lt;\/filter-name&gt;<br \/>\n        &lt;url-pattern&gt;\/*&lt;\/url-pattern&gt;<br \/>\n    &lt;\/filter-mapping&gt;<\/p>\n<p>    &lt;filter-mapping&gt;<br \/>\n        &lt;filter-name&gt;sitemesh&lt;\/filter-name&gt;<br \/>\n        &lt;url-pattern&gt;\/*&lt;\/url-pattern&gt;<br \/>\n        &lt;dispatcher&gt;REQUEST&lt;\/dispatcher&gt;<br \/>\n        &lt;dispatcher&gt;ERROR&lt;\/dispatcher&gt;<br \/>\n    &lt;\/filter-mapping&gt;<br \/>\n[\/code]<\/p>\n<p style=\"text-align: left;\">You can add your own filter mapping just after the <code>charEncodingFilter<\/code>. Some plugins creates their filter just before the <code>sitemesh<\/code> filter but not all. They add their filters after the <code>charEncodingFilter<\/code>. Thus again defeating our purpose of executing our filter at top of the chain. It is strongly advised that don&#8217;t put your filter before <code>charEncodingFilter<\/code>. To solve this problem we would have to create a new plugin in our project.<\/p>\n<h3 style=\"text-align: left;\">2. <span style=\"text-decoration: underline;\">Using Plugin<\/span><\/h3>\n<p style=\"text-align: left;\">To create a plugin just run the command <code>grails create-plugin [PLUGIN NAME]<\/code>. Now open *GrailsPlugin.groovy file. Here you will find a closure with the name <span style=\"text-decoration: underline; color: black;\">doWithWebDescriptor<\/span>. Here we can declare our filter and define its mappings. Note that defining the mapping here will not effect the ordering in web.xml as webxml plugin is responsible for managing the ordering of filters in web.xml file. After adding your filter code in doWithWebDescriptor would look like this:<\/p>\n<p>[code lang=&#8221;groovy&#8221;]<br \/>\ndef doWithWebDescriptor = {<br \/>\n\txml -&gt;<br \/>\n\t\tdef contextParam = xml.&#8217;context-param&#8217;<br \/>\n\t\tcontextParam[contextParam.size() &#8211; 1] + {<br \/>\n\t\t\t&#8216;filter&#8217; {<br \/>\n\t\t\t\t&#8216;filter-name'(&#8216;myCustomFilter&#8217;)<br \/>\n\t\t\t\t&#8216;filter-class'(com.ttnd.filter.MyFilterClass.name)<br \/>\n\t\t\t}<br \/>\n\t\t}<\/p>\n<p>\t\tdef filterMappings = xml.&#8217;filter-mapping&#8217;<br \/>\n\t\t\/\/ webxml plugin is responsible for filter mapping order.  Put the filter mapping anywhere.<br \/>\n\t\tfilterMappings[filterMappings.size() &#8211; 1] + {<br \/>\n\t\t\t&#8216;filter-mapping&#8217; {<br \/>\n\t\t\t\t&#8216;filter-name'(&#8216;myCustomFilter&#8217;)<br \/>\n\t\t\t\t&#8216;url-pattern'(&#8216;\/*&#8217;)<br \/>\n\t\t\t\t&#8216;dispatcher&#8217; &#8216;REQUEST&#8217;<br \/>\n\t\t\t\t&#8216;dispatcher&#8217; &#8216;ERROR&#8217;<br \/>\n\t\t\t}<br \/>\n\t\t}<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: left;\">Now we have to define the order of our filter. Add a method <code>getWebXmlFilterOrder<\/code> in this file. webxml plugin uses this method to identify the position of your filter in web.xml. Here is the code snippet:<\/p>\n<p>[code lang=&#8221;groovy&#8221;]<br \/>\ndef getWebXmlFilterOrder() {<br \/>\n\tlog.debug(&quot;Start getWebXmlFilterOrder&quot;)<br \/>\n\tdef filterMap = [:]<br \/>\n\ttry {<br \/>\n\t\tdef classLoader = new GroovyClassLoader(getClass().getClassLoader())<br \/>\n\t\tdef FilterManager = classLoader.loadClass(&#8216;grails.plugin.webxml.FilterManager&#8217;)<br \/>\n\t\tlog.debug(&quot;set WebXmlFilterOrder after char encoding filter&quot;)<br \/>\n\t\t\/\/grails.plugin.webxml.FilterManager class holds the position of default grails filters.<br \/>\n\t\t\/\/Use this class to fetch the position of charEncodingFilter and put our filter just after that.<br \/>\n\t\tfilterMap = [myCustomFilter: FilterManager.CHAR_ENCODING_POSITION]<br \/>\n\t} catch (ClassNotFoundException e) {<br \/>\n\t\tlog.error &quot;Could not determine desired nimbusFilter position.&quot;<br \/>\n\t}<br \/>\n\treturn filterMap<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: left;\">Now you would be asking to yourself that aren&#8217;t other plugins use same method to put their filter just after the charEncodingFilter.<br \/>\nYes, you are right. They do follow the same method. So how can we put our filter before their filter?<\/p>\n<p>Answer is <strong>loadAfter<\/strong>. You will find a variable declared with name loadAfter within the same plugin file. Here we can add the artifact names or plugin names after which we want our plugin methods to execute. So if you are using shiro plugin for security purpose, you would add its name to this field. Here is a code snippet:<\/p>\n<p>[code lang=&#8221;groovy&#8221;]<br \/>\ndef loadAfter = [<br \/>\n\t&#8216;hawk-eventing&#8217;,<br \/>\n\t&#8216;hibernate-hijacker&#8217;,<br \/>\n\t&#8216;shiro&#8217;,<br \/>\n\t&#8216;core&#8217;,<br \/>\n\t&#8216;dataSource&#8217;<br \/>\n]<br \/>\n[\/code]<\/p>\n<p style=\"text-align: left;\">That&#8217;s all. Now your filter will be invoked first in filter chain. Cheers!!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sometimes in a web application we need filtering on request to a resource or on response, or on both. In Grails, it could be done easily via creating a filter. Just run grails create-filters [filter-name] and it will generate a filter in the application. To run a filter before all other filters, just put that [&hellip;]<\/p>\n","protected":false},"author":182,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":27},"categories":[7,1],"tags":[4840,2045,1062,2044,2043],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/23997"}],"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\/182"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=23997"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/23997\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=23997"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=23997"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=23997"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}