Recently I wanted to use the Tuckey UrlRewriteFilter. It is described as: A Java Web Filter for any compliant web application server, which allows you to rewrite URLs before they get to your code.

I wanted to load my urlrewrite.xml as a Spring (classpath) resource, instead of loading it from the default location provided by the UrlRewriteFilter. The default behavior loads the configuration file from /WEB-INF/ulrewrite.xml. In my case I wanted to load it from the /src/main/resources folder, which is the root of my classpath.

import org.springframework.core.io.Resource;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;

//Adding @Component Annotation to a Filter is enough to register the Filter, when you have no web.xml
@Component
public class MyUrlRewriteFilter extends UrlRewriteFilter {

    private static final String CONFIG_LOCATION = "classpath:/urlrewrite.xml";

    //Inject the Resource from the given location
    @Value(CONFIG_LOCATION)
    private Resource resource;

    //Override the loadUrlRewriter method, and write your own implementation
    @Override
    protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
        try {
            //Create a UrlRewrite Conf object with the injected resource
            Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "@@yourOwnSystemId@@");
            checkConf(conf);
        } catch (IOException ex) {
            throw new ServletException("Unable to load URL rewrite configuration file from " + CONFIG_LOCATION, ex);
        }
    }
}

With this small and easy to use decorated UrlRewriteFilter, you can load your configuration from any location. When you write a UnitTest for this decorated Filter, don't forget to call the init() method before you call the actual doFilter(). For testing your UrlRewriteFilter rules, it is better to write an IntegrationTest, for example with the [TestRestTemplate](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/TestRestTemplate.html)

shadow-left