Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

servlets

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

like image 345
Bibhaw Avatar asked Jan 26 '11 07:01

Bibhaw


People also ask

What does servlet context do?

Interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

What do you mean by context initialization parameters?

The context initialization parameters are common and accessible to all the servlets in an application and hence are also called the application parameters. The context initialization parameters are set in the deployment descriptor file, web.xml.

How many ServletContext objects are available for?

There is only one ServletContext object per web application.


1 Answers

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.

like image 170
leonm Avatar answered Oct 15 '22 13:10

leonm