Steve Kuo
Steve Kuo

Reputation: 63054

urlrewrite using Servlet filter

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.

Upvotes: 2

Views: 4636

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128779

Just wrapping the request and changing its state isn't sufficient. You'll need to forward/redirect to the appropriate resource. Filters and servlets are mapped to a URL pattern. The chain you're executing in was built based on the pattern of the incoming request's URL. Changing the URL in the request and passing it to the next item in the chain isn't going to rebuild the chain to account for the new URL. That's what a forward/redirect is for.

Upvotes: 2

Related Questions