If you start your relative link with a slash "/" then the browser will look in the root of the site (ignoring your contextPath). If there is no preceeding slash the browser will look in (what it perceives to be) the current directory.
The most solid way to build your relative urls, in my opinion is to read the contextPath from the request object.
In this example, there are 3 ways you can send the url for myImage.png to the browser:
An absolute URL: http://localhost:8080/myApp/images/myImage.pngIn this case, you're giving the browser everything it needs to find your image.
A relative URL: images/myImage.png
In this case, you're telling the browser to add the current path to the beginning of this relative URL.
A URL that is relative to the root of the website:
/myApp/images/myImage.png In this case, you're telling the browser to add the current domain:port combination to the beginning of the absolute url.
Browsers don't know anyting about the concept of a Java webapp. They don't know that a J2EE app server can house multiple apps and that it uses the first directory entry as the name (contextPath) for the webapp. They only know to add the current domain:port to the beginning of a relative URL if that relative URL starts with a slash.
You have to add the contextPath to the beginning of your URLs.
Originally posted by Reema Patel: But, wat about the 1001 books that give URL like the one I have submitted....eg. /results.jsp...I'm yet to see anybody prefexing the app name...
Most books, in a mis-guided attempt to keep things simple, assume that you will be replacing Tomcat's root web app with your own.
The root web has a context path of "/".
Joined: Jan 26, 2006
Thanks Bear! This means that if I don't explicitly give my app name, it by default looks inside the ROOT web app, and since there's no such resource with a matching name, I get a page not found 404 error.