context path in servlet

I have a file located in Tomcat/webapps/myapp/custom/xsl/abc.xsl

How can I get the context path, so that I just append custom/xsl/abc.xsl to it and get to the file.
Who is Participating?
request.getContextPath() will return you the URI context of a request (that is, the URI realtive to the server). In your case, that would equate to "/custom/xsl" assuming that your myapp is configured to be at the context root ("/").

If you're after the actual path to a file in the machine filesystem, you can use the getRealPath function in the ServletContext (see )

In your case, inside your servlet call getServletContext().getRealPath("/custom/xsl/abc.xsl");

There are some warnings attached to using this method (as you can see in the javadoc). For instance, of you package your webbapp in a WAR archive, getRealPath won't work.

A more "proper" way to go about this is to use the getResourceAsStream function (see ). This will give you an InputStream from which you can read the content of any file inside your webapp.

//Inside your servlet
InputStream is = getServletContext().getResourceAsStream("/custom/xsl/abc.xsl");

Open in new window

chaitu chaituCommented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.