Sunday, May 20, 2007

servletContext.getRealPath() issue

Our application was using getRealPath() method to obtain the base path of the web application on the server. I noticed that the method was not behaving consistently across JEE containers.
On Windows/Tomcat5.5, getRealPath returned the path with a '/' at the end.
But on Solaris/Websphere, getRealPath returned the path without a '/' at the end.

The best way to handle this is to have a utility method that would handle all cases :-
String realPath = 
getServletContext.getRealPath(path);

if ((realPath != null)
&& !realPath.endsWith("/"))
realPath += "/";
Also check if using getRealPath is really required. The Servlet API specifies a temp directory that can be accessed using the following code:
File dir=(File)getServletContext().getAttribute
("javax.servlet.context.tempdir");

No comments:

Post a Comment