Get resource folder in java war file

Henrique Gonçalves picture Henrique Gonçalves · Jan 15, 2013 · Viewed 8k times · Source

I'm creating a REST webservice that uses keyczar for encryption. I've generated both public and private keys and placed them under src/main/resources/RSA.

To instantiate the encrypter I need to pass to it the location of the files like Crypter crypterPrivate = new Crypter(PATH_RSA + "/private"); but I'm having problems with the RSA folder location when I deploy the war file.

I've tried some stuff I've googled like InputStream but it is not this case since I don't want to pass any file but the RSA folder location. Also have tried several different folders like /WEB-INF/classes/RSA (it's where is located in war file).

Any tips? Thank you

Answer

Ian Roberts picture Ian Roberts · Jan 15, 2013

If keyczar can take a URL for its key location then this.getClass().getResource("/RSA/private") will give you a suitable URL. If it requires a native file path then you'll have to use

ServletContext ctx = // ...
String pathToKey = ctx.getRealPath("/WEB-INF/classes/RSA/private");

Exactly how you get hold of the ServletContext depends on your toolkit. Note that this will only work if the WAR file is expanded on disk when you deploy it, it won't work if the app is running directly from the compressed WAR file.