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.
angela_smithAsked:
Who is Participating?
 
pellepCommented:
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 http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String) )

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 http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String) ). 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

0
 
chaitu chaituCommented:
request.getContextPath()/custom/xsl/abc.xsl;
0
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.