How can I get the name of the current web application in Java EE?

How can I get the name of the current web application in Java EE?

I am quite comfortable working with stand-alone Java, but Java EE is new to me. I am writing some kind of custom code to connect to a third-party Java EE reporting package. I have several instances deployed on the same Tomcat server, so I have something like:

  C: \
 + - tomcat6
     + - webapps
         + - app1
         + - app2

So, when the user goes, say, http://example.com/app1/viewReport , I want to get "application1". (And not by parsing the URL.)

Also, if there was a way to get the root from app1 (in this example C: \ tomcat6 \ webapps \ app1), that would be great too.

+6
java java-ee tomcat
source share
2 answers

1. Getting the "name"

He called the path of context. If the code works in the context of a web application request, you can get it by calling HttpServletRequest#getContextPath() .

2. Access to a physical / real resource

If you are trying to access the contents of a file / resource in your web application, your best bet is to use one of:

You can also get the physical path on the disk of the file / resource, given the path relative to the web application using ServletContext#getRealPath(String) , but it is not reliable (it does not always work if, for example, you deploy webapp as a WAR).

3. Access to class path resources

In your comment, you tried to access the resource in the directory / WEB -INF / classes. Since WEB-INF / classes / * are web application classes, you can simply access it as if you were accessing any resource of the class path in a Java SE application. Again, if your code is running in a webapp context, you can simply use the following:

In your case, you probably want to use the latter, and then load the properties file by loading properties # (InputStream).

Something along the lines of:

 Properties props = new Properties(); props.load(getClass().getResourceAsStream("/reportCustom.properties")); 
+11
source share

what I'm trying to do is load the properties file in webapps / myapp / WEB-INF / classes / reportCustom.properties

Since the file is located in the classes directory, it can be loaded using ClassLoader (the usual Java mechanism for loading files in the classpath). It is probably best to use a ClassLoader context .

+2
source share

All Articles