title: Servlet filters' order of execution
body: <p>I stumbled upon a bug in my web application that had me  scratching my head (and eventually pulling my hair) for a while before I found out what was going on.</p>
  
  <p>Basically, I had 2 filters defined in my web.xml, and the two mappings like that :</p>
  
  <pre><code>&lt;filter-mapping&gt;
      &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
      &lt;servlet-name&gt;SpringMVCDispatcher&lt;/servlet-name&gt;
  &lt;/filter-mapping&gt;
  
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;SpringFormMethodFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/administration/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>They are both Spring MVC filters. My problem was that the form data I got was not interpreted as UTF-8 despite the fact that the encodingFilter was supposed to set the request encoding to UTF-8 before anything else had the opportunity to read from it. </p>
  
  <p>I finally noticed that the form method filter was executed BEFORE the encoding filter, although the order in which filter mappings are defined is supposed to be the order in which they are chained : </p>
  
  <blockquote>
    <p>The order of the filters in the chain is the same as the order that
    filter mappings appear in the web application deployment descriptor.</p>
  </blockquote>
  
  <p>(from <a href="http://www.oracle.com/technetwork/java/filters-137243.html">Oracle</a>)</p>
  
  <p>When I used the same mapping, i.e. mapping to a servlet instead of a URL pattern, for both mappings, the order is restored and everything works as intended:</p>
  
  <pre><code>&lt;filter-mapping&gt;
      &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
      &lt;servlet-name&gt;SpringMVCDispatcher&lt;/servlet-name&gt;
  &lt;/filter-mapping&gt;
  
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;SpringFormMethodFilter&lt;/filter-name&gt;
      &lt;servlet-name&gt;SpringMVCDispatcher&lt;/servlet-name&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>Is that part of the <code>Servlet</code> specification or is it a glitch of Tomcat ? Is it documented somewhere, should I submit a bug report ?</p>
  
  <p>I am using Tomcat 7.0.39 with Java 7.</p>