Handling context-path refs when migrating “/” site to Java EE packaging
-
02-07-2019 - |
Question
An existing Java site is designed to run under "/" on tomcat and there are many specific references to fixed absolute paths like "/dir/dir/page".
Want to migrate this to Java EE packaging, where the site will need to run under a context-root e.g. "/dir/dir/page" becomes "/my-context-root/dir/dir/page"
Now, the context-root can be easily with ServletRequest.getContextPath(), but that still means a lot of code changes to migrate a large code base. Most of these references are in literal HTML.
I've experimented with using servlet filters to do rewrites on the oubound HTML, and that seems to work fine. But it does introduce some overhead, and I wouldn't see it as a permanent solution. (see EnforceContextRootFilter-1.0-src.zip for the servlet filter approach).
Are there any better approaches to solving this problem? Anything obvious I'm missing? All comments appreciated!
Solution
Check out a related question
Also consider URLRewriteFilter
Another thing (I keep editing this darn post). If you're using JSP (versus static HTML or something else) you could also create a Tag File to replace the common html tags with links (notably a, img, form). So <a href="/root/path">link</a> can become <t:a href="/root/path">link</t:a>. Then the tag can do the translation for you.
This change can be easily done "en masse", using something like sed.
sed -e 's/<a/<t:a/g' -e 's/<\/a>/<\/t:a>/g' old/x.jsp > new/x.jsp
Form actions may be a bit trickier than sed, but you get the idea.
OTHER TIPS
the apache world used Redirects(mod_rewrite) to do the same.
The Servlet world started using filters
The ruby world (or the RoR) does more of the same stuff and they call it routing.
So, there's no getting around it (Unless you want to use smart regex through out -- which has been tried and it works just fine).