Tomcat: correct way to find a resource? [duplicate]
I've working on a big application deployed on a Tomcat server. There's only one .jsp page and all the UI is done using ext-js.
There are a lot of .java classes. In one of these class (which is performing validation), I'd like to add XML validation and to do this I need to access the .xsd file.
My problem is that I don't know how to cleanly find the path to my .xsd file.
I'll put the .xsd files in a repertory next to css/, images/, etc.
I know how to this in a crappy way: I call System.getProperty("user.home") and from there I find my webapp, the xsd/ folder, and the .xsd files.
But what is a "clean" way to do this?
Where am I supposed to find the path to my webapp (or to my webapp resources) and how am I supposed to pass this information down to the .java class that performs the validation?
For files in public web content the ServletContext#getRealPath()
is indeed the way to go.
String relativeWebPath = "/path/to/file.xsd";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// ...
However, I can't imagine that there is ever intent to serve the XSD file into the public and also the Java class which needs the XSD doesn't seem to be a servlet. So, I'd suggest to just put XSD file in the classpath and grab from there instead. Assuming that it's been placed in the package com.example.resources
, you can load it from the classpath as follows:
String classpathLocation = "com/example/resources/file.xsd";
URL classpathResource = Thread.currentThread().getContextClassLoader().getResource(classpathLocation);
// Or:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathLocation);
getServletContext().getRealPath("/")
is what you need.
See here.
精彩评论