Tomcat: the right way to find a resource?

I am working on a large application deployed on a Tomcat server. There is only one .jsp page and the entire user interface is executed using ext-js.

There are many .java classes. In one of these classes (which performs validation) I would like to add XML validation, and for this I need to access the .xsd file.

My problem is that I do not know how to find the path to my .xsd file correctly.

I will put the .xsd files in the repertoire next to css /, images / etc.

I know how this is in a shitty way: I call System.getProperty ("user.home"), and from there I find my webapp file, xsd / folder and .xsd.

But what is the β€œclean” way to do this?

Where should I find the path to my webapp (or my webapp resources) and how should I pass this information to the .java class that performs the check?

+3
source share
2 answers

For files in public web content it ServletContext#getRealPath()really suits.

String relativeWebPath = "/path/to/file.xsd";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// ...

However, I cannot imagine that I ever intend to serve an XSD file in a public environment, and the Java class that needs XSD does not seem to be a servlet. So, I would suggest just putting the XSD file in the classpath and grab it there. Assuming it was placed in a package com.example.resources, you can load it from the class path as follows:

String classpathLocation = "com/example/resources/file.xsd";
URL classpathResource = Thread.currentThread().getContextClassLoader().getResource(classpathLocation);
// Or:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathLocation);
+10
source

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

See here .

+1

Source: https://habr.com/ru/post/1792298/


All Articles