I understand that using a relative URL as the value for an HTML href attribute is usually considered A Good Thing To Do. However, is there a way to make relative URLs work reliably in combination with
servlet "path mapping"? Here's a problem situation...
MyServlet produces an HTML page that uses a relative URL to locate a stylesheet, like this:
<link type="text/css" href="style/plain.css">
The web.xml for myapp uses path mapping, like this:
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet/*<url-pattern>
</servlet-mapping>
The problem is that sometimes the browser can find the stylesheet, and sometimes it can't, depending on what URL is used to connect to the servlet.
If you point the browser to
http://localhost:8180/myapp/Servlet1, the stylesheet can be found. With that base URL, the relative URL style/plain.css points to
http://localhost:8180/myapp/style/plain.css, which is where the stylesheet really is.
However, if you point the browser to
http://localhost:8180/myapp/Servlet1/ (note the trailing slash) the stylesheet is not found, because the relative URL then points to a non-existent location,
http://localhost:8180/myapp/Servlet1/style/plain.css Eventually, I resorted to constructing an absolute URL for the stylesheet, using code like this:
URL x = new URL( req.getRequestURL().toString() );
String href = x.getProtocol() + "://" + x.getHost() +
":" + x.getPort() + req.getContextPath() +
"/style/plain.css"
That worked, but was it necessary? Are there other ways to handle it? Any thoughts will be much appreciated.
John