15.4 Interpreting Relative URLs in the Destination Page
Although a servlet can forward the request to an arbitrary location on the same server, the process is quite different from that of using the sendRedirect method of HttpServletResponse . First, sendRedirect requires the client to reconnect to the new resource, whereas the forward method of RequestDispatcher is handled completely on the server. Second, sendRedirect does not automatically preserve all of the request data; forward does. Third, sendRedirect results in a different final URL, whereas with forward , the URL of the original servlet is maintained .
This final point means that if the destination page uses relative URLs for images or style sheets, it needs to make them relative to the servlet URL or the server root, not to the destination page's actual location. For example, consider the following style sheet entry:
<LINK REL=STYLESHEET HREF="my-styles.css" TYPE="text/css">
If the JSP page containing this entry is accessed by means of a forwarded request, my-styles.css will be interpreted relative to the URL of the originating servlet, not relative to the JSP page itself, almost certainly resulting in an error. The simplest solution to this problem is to give the full server path to the style sheet file, as follows .
<LINK REL=STYLESHEET HREF="/path/my-styles.css" TYPE="text/css">
The same approach is required for addresses used in <IMG SRC=...> and <A HREF=...> .