Reputation: 3742
I only hardcode the location in web.xml, but it makes us need to change the web.xml everytime during deployment.
Can we make a folder inside the project and tell the servlet to look for the folder and the file underneath it?
<context-param>
<param-name>ipTable</param-name>
<param-value>E:\Workspace\Eclipse_Workspace\BpsPdfBill\WebContent\WEB-INF\ipTable.txt</param-value>
</context-param>
Upvotes: 1
Views: 133
Reputation: 8839
If you don't need a File
object, you can use ServletContext.getResource(String path)
. The path
argument must begin with '/', and is relative to context root. The method returns a URL
, which you can open and then read the contents of the file.
I don't think there is a standard method of getting a pointer to a File
object. You could always use a system property, but that's probably no better than putting it in the web.xml
.
UPDATE
If you really need a File
object, and not just the contents of the file, there are a couple of things you can do. It depends on how the location of the file changes.
If the file location changes based on the server you are deploying to, but it stays the same on each server, then just add a system property to your web container's startup scripts. How you do this, of course, varies by container, but you should be able to find out how in the documentation.
You could also put the location of the file in a separate properties file, say file.properties
, and modify your deployment process to generate or update this file and place it in your WEB-INF
directory. Then you can read this properties file with ServletContext.getResourceAsStream()
, get the path, and instantiate the File
.
Upvotes: 2
Reputation: 21684
There are two reasons I have to be able to OS path of a file from my servlet. If your objectives coincide with mine, this might be the answer.
To achieve that I place the file in a directory under the war under a known URL. Let's say URL is /data/asdf.txt. I could even store this as a web.xml param. Then I use
ServletContext.getRealPath(/data/asdf.txt)
to get the OS path. Even though I hard-code the param in web.xml, the path of the file moves with deployment.
To hide a folder from URL access, I prefix the folder with "~" in Tomcat. I think the character is "~", cannot recall. You need to try it out. With that character as prefix, it was impossible for the server to serve the contents with that URL. I might come back to update the answer when I dig my past codes to find out the prefix.
Of course, the other way to hide your folder is to place it in WEB-INF.
Upvotes: 0