• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting path to resources in servlet

 
Wes Hughes
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65530
108
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
hth,
bear
 
Wes Hughes
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
I think I like the File idea, nice and general.
 
Matthew Phillips
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!