users@glassfish.java.net

Re: Rewriting URLs to change servlets?

From: <Jan.Luehe_at_Sun.COM>
Date: Tue, 07 Aug 2007 18:09:53 -0700

Robin,

Jan.Luehe_at_Sun.COM wrote:

> Hi Robin,
>
> Robin Sheat wrote:
>
>> On Tuesday 07 August 2007 07:36:41 glassfish_at_javadesktop.org wrote:
>>
>>
>>> Yes, this is exactly what has happened. The container has already
>>> decided
>>> what to do before it invokes your filter. (That's why it knows to
>>> invoke
>>> your filter, in fact -- it's kind of a catch-22.)
>>>
>>
>> Yeah, it does make sense.
>>
>>
>>
>>> The hot tip to get around this is to FORWARD to your new URL, and
>>> then it
>>> will work as expected.
>>>
>>
>> How do you forward to a new URL? I can't do a browser redirect or
>> anything, because that would lose the information I need. Is there an
>> internal way to forward requests? I guess it would be like passing it
>> in to the dispatch system again or something.
>>
>>
>
> have you tried wrapping the request in your filter, in such a way
> that the request wrapper overrides the relevant request path methods to
> perform the manipulations you want?
>
> For example, in your doFilter() method, you could wrap the request as
> follows:
>
> filterChain.doFilter(
> new MyHttpServletRequestWrapper((HttpServletRequest) request),
> response);
>
> where the request wrapper overrides getServletPath() to remove any
> "/partition"
> component, as follows:
>
> class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
>
> private HttpServletRequest request;
>
> public MyHttpServletRequestWrapper(HttpServletRequest request) {
> super(request);
> this.request = request;
> }
>
> public String getServletPath() {
> String servletPath = request.getServletPath();
> if (servletPath != null &&
> servletPath.startsWith("/partition/")) {
> servletPath =
> servletPath.substring("/partition".length());
> }
> return servletPath;
> }
>
> }
>

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
root, so with the above request wrapper in place, something like:

  http://<host>:<port>/<context_root>/partition/static.html

will be mapped to

  http://<host>:<port>/<context_root>/static.html

which is what you want, if I understood correctly.


Jan