6

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?

Gugussee
  • 1,673
  • 3
  • 16
  • 26

2 Answers2

15

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);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks a lot. In the second case, is it good practice to just drop the file on the classpath? (I'll probably have a new question regarding how to do this) – Gugussee Feb 16 '11 at 09:36
  • It's certainly a normal practice for resources of Java classes. The classpath is there where your Java classes also are :) Create a package or reuse an existing package and put the XSD file there. That's it. – BalusC Feb 16 '11 at 11:45
2

getServletContext().getRealPath("/") is what you need.

See here.

Yoni
  • 10,171
  • 9
  • 55
  • 72