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?
A classpath is an argument that tells the JVM where to find the classes and packages necessary to run a program. The classpath is always set from a source outside the program itself.
you can upload the . jar's to /home/tomcat/lib, which is mentioned in this doc. /home/tomcat/lib is added to Tomcat's class loader, so the . jar will be added just like when you put it under CATALINA_HOME/lib." Hope that helps.
Tomcat JAR deployment options Package the JAR file in the WEB-INF\lib folder of the Java web application; Place the JAR file in the \lib subfolder of the Apache Tomcat installation; Configure a folder for shared JAR files by editing Tomcat's common.
Tomcat (and a lot of other web containers / application servers) load the application with separate ClassLoader hierarchies. This isolates all classes against other (web) applications and thus also makes sure, that singletons, different class versions and all this stuff does not collide.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With