Search code examples
javajsptomcaturl-routingfriendly-url

URL routing and relative links in Tomcat 5.5


I'm trying to add URL routing to a web application running in Tomcat 5.5.

I want to make the dynamic page URLs more friendly, changing main.jsp?type=test&group=info to main/test/info as is all the rage.

I have set up the following in the web.xml

  <servlet>
    <servlet-name>main</servlet-name>
    <jsp-file>/main.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>main</servlet-name>
    <url-pattern>/main/*</url-pattern>
  </servlet-mapping>

and in main.jsp I use request.getPathInfo() to get the data that I need to do the routing. All this seems to work fine, and when I browse to http://mytestserver/example/main/test/info I get the html that I expect.

The problem is that any relative links on that page, images, style-sheets, javascript, etc., are now all broken, as they are being interpreted as relative to the full URL.

I can't think of an easy way to use static links because the URLs on the test server and production server are at different levels: http://mytestserver/example/ maps to http://example.com/ in production, and I really do not want to have to write code to wrap every internal link on the site or set up a virtual server for each site on the test server.

Is there anything else I can do?


Solution

  • I have a system like this at work.

    We use a package called urlrewrite, which basically is the apache tomcat rewriter done up as a j2ee filter. It's cool, but I ran into this same problem.

    To fix it, I wrote another filter which is inserted into the filter chain before the rewriter. Its job is to grab the pathinfo before the rewriter mangles it, and to stick that info into a request attribute. It resolves the pathinfo of the request against the pathinfo of the web application root, to work out how many "../" you need to get to the root of the web app (from the client's point of view).

    The other components of the system then use the content of that attribute to build their relative urls. Works great.

    The system is here.

    Look for any taxon (MACROPODIDAE is a fine choice). All the rest-y looking links get turned into reqest parameters by the url remapper.