Forums Register Login
Getting path to resources in servlet
This is a question of implementation and best practices. I instantiate Class A inside my servlet, which in turn instantiates Class B. The problem is that Class B needs to load xslt stylesheets from WEB-INF/xslt. What is the best way for Class B to know where to load the sheets from? Right now I'm using context.getRealPath("/") within the servlet and then passing the path into Class A and subsequently Class B. Is there a better way to do this? Should I pass the context around instead?
I don't have this problem with my properties files, which are in the classes directory, where I can use getClass().getResourceAsStream("fileName"). I don't think this works outside the classes directory, however. Using Tomcat, btw.
Thanks in advance.

Should I pass the context around instead?

By doing so, you make the classes servlet-environment dependent. If they are already servlet-aware for other reasons, no harm done. But if not, limiting them to the servlet environment just so you can pass the context around would be considered a poor practice.
In such cases, I generally create a File instance indentifying the file/resource and pass that to other classes which I keep as generic as possible.
I think I like the File idea, nice and general.
You could code the actual path to the file as an init-param and use it to instantiate your file. Then if the path changes, you would not need to recompile.
All of the following truths are shameless lies. But what about this tiny ad:
Why should you try IntelliJ IDEA ?

This thread has been viewed 504 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 22, 2018 03:08:10.