Bibhaw
Bibhaw

Reputation: 497

Servlet : What exactly the use of context.getRealPath(" ");

As i know it returns the application path? But what exactly the use of it.

Upvotes: 5

Views: 4789

Answers (4)

J K
J K

Reputation: 1687

The getRealPath() gives the absolute path (on the file system) leading to a file specified in the parameters of the call. It returns the path in the format specific to the OS. The getContextPath() on the other hand returns the URI or the relative path to the resource.

Upvotes: 2

AlexR
AlexR

Reputation: 115398

This is a real path in file system.

From javadoc:

The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

I think it is very clear. Why do we need this? Sometimes web applications perform some manipulation in file system. For example read stuff from files, write files etc. This API allows you to access the place where your JSPs and other stuff is really stored.

Upvotes: 1

slhck
slhck

Reputation: 38770

As far as I remember, I've used it to save images or other data files, since it allows you to see where your application is deployed at the moment. For example, Eclipse and Tomcat will create a temporary folder that's buried deep somewhere within your Eclipse profile and deploy the app there.

Upvotes: 1

leonm
leonm

Reputation: 6484

In many environments the application user is not allowed to read any files outside of the deployment directory. This is mostly done for security purposes - for example if someone hacks your application they won't be able to read a passwords file.

And in professionally managed environments developers often don't have a say in which directory the application will be placed.

So if you need to read a file like properties, images, certificates, etc. you can place it in the application directory (or .war file) and use getRealPath("") to get the path you need to load.

As an alternative you can place the external files on the classpath but there are sometimes issues with this. For large files most app servers will try to load the entire file into memory and cache it if it is on the classpath.

Upvotes: 5

Related Questions