How do I prepend <%= request.getContextPath() %> to all relative URLs inside a jsp page?
Question
The subject says it all, almost. How do I automatically fix jsp pages so that relative URLs are mapped to the context path instead of the server root? That is, given for example
<link rel="stylesheet" type="text/css" href="/css/style.css" />
how do I set-up things in a way that maps the css to my-server/my-context/css/style.css
instead of my-server/css/style.css
? Is there an automatic way of doing that, other than changing all lines like the above to
<link rel="stylesheet" type="text/css"
href="<%= request.getContextPath() %>/css/style.css" />
Solution
Look into the <BASE HREF="">
tag. This is an HTML tag which will mean all links on the page should start with your base URL.
For example, if you specified <BASE HREF="http://www.example.com/prefix">
and then had <a href="/link/1.html">
then the link should actually take you to /prefix/link/1.html. This should also work on <LINK>
(stylesheet) tags.
OTHER TIPS
The better way is to HttpServletResponse.encodeURL() which will construct the url appropria