I'm trying to write a simple urlrewriter using Servlet's filter (javax.servlet.Filter
). The filter inspects all requests and reroutes to servlet (or JSP) depending on the URL.
Example: http://server/app/person/Roscoe would be translated to http://server/app/person.jsp?name=Roscoe
My Filter
's doFilter
inspects the request, and if the pattern matches, creates a new HttpServletRequest
and passes it to chain.doFilter
. The new HttpServletRequest
extends javax.servlet.http.HttpServletRequestWrapper
and overrides the parameters, URI, URL, query string, and servlet path to look like the new JSP (/person.jsp?name=Roscoe
). I thought that by passing the new request to chain.doFilter
it would redirect to the JSP. This works, sort of, except that the contents of person.jsp
are returned to the browser. person.jsp
never executes the contents are returned as plain text (Content-Type: text/plain
).
My web.xml
has the filter and filter-mapping:
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Is this the correct was to use a Servlet filter to rewrite the request?
I am aware of existing urlrewriters (such as Tuckey) but would still like to write my own, mainly to learn and for better control.
Follow-up: I've also tried redirecting instead of chain.doFilter
by doing (where req
is the wrapped request):
config.getServletContext().getRequestDispatcher("/person.jsp").forward(req, resp);
This works better, but my CSS file (styles.css
) is still relative to original URL http://server/app/person/styles.css, whereas it should be http://server/app/styles.css
Follow-up 2: The path issue is covered by this question.