users@glassfish.java.net

Re: Rewriting URLs to change servlets?

From: <Jan.Luehe_at_Sun.COM>
Date: Mon, 13 Aug 2007 17:59:52 -0700

Hi Robin,

Robin Sheat wrote:

>On Wednesday 08 August 2007 13:09:53 Jan.Luehe_at_sun.com wrote:
>
>
>>Some additional explanation: In the case of static resources,
>>which are not mapped to any servlet declared in a webapp's web.xml
>>(they're handled by an implementation-specific servlet),
>>request.getServletPath() returns the request's URI minus the context
>>
>>
>Hmm, it looks like I spoke too soon, and didn't pay enough attention to what
>you said. It does work fine for static resources, however I also need it to
>work for servlets. Is this possible?
>
>Actually, in pseudo-regex terms, I just want:
>/app/([^/]*)/something
>to become:
>/app/something
>and where the bit in brackets can be retrieved by the servlet 'something'.
>
>

OK, for this to work, your best bet would be to forward dispatch the
request to the target resource, i.e.:

public class MyFilter implements Filter {

    private ServletContext context;

    public void doFilter(ServletRequest req,
                                    ServletResponse res,
                                    FilterChain filterChain)
            throws IOException, ServletException {

        context.getRequestDispatcher(<target_resource>).forward(req, res);

    }

    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
    }
}

However, make sure your filter is *not* invoked during FORWARD,
or else you will end up in an endless loop. In other words, in your
<filter-mapping>, don't specify any <dispatcher> element, or if you
do, make sure FORWARD is not amongst them. :)


Jan