School Boy
School Boy

Reputation: 1183

Read common external property file in Java Webapp and java normal app

I know this question has answered many a time with most useful answer as below,

Where to place and how to read configuration resource files in servlet based application?

However, We have some special requirement as below,

  1. Webapp will be deployed to tomcat.
  2. Normal java app in form of .jar will be placed under folder /myapp
  3. myappConfig.property file will be placed under /myapp

Directory Structure on client machine

/myapp
   /myapp.jar
   /assests/myappConfig.property
   /tomcat/webapps/myapp.war

Basically myapp.jar and myapp.war will access sql db connection values for MySql database connection and db operations.

Accessing myappConfig.property from myapp.jar --> Working fine

        File jarPath = new File(Myapp.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath = jarPath.getParent();
        System.out.println(" propertiesPath-" + propertiesPath);
        mainProperties.load(new FileInputStream(propertiesPath + "\\assets\\myapp.property"));

Can anyone help/suggest how to implement,

Accessing myappConfig.property file from mywebapp,

provided run time change in myappConfig.property file does not required myapp.war to be redeployed

Thanks for your help in advance.

edit

Below is the steps in which we want to deliver the project to client.

  1. Below is my app directory

    /myapp
      /myapp.jar
      /assests/myappConfig.property
      /tomcat/webapps/myapp.war
    
  2. pack everything in one package with some packaging tool.

  3. Run this package in client machine at any location and it will have same directory structure as above

  4. Here, I do not want to hard code any location in webapp or tomcat for "/assests/myappConfig.property"

  5. Normal Java app I can read property file but for wepapp I am not getting clear idea for how to do that?

Upvotes: 0

Views: 2997

Answers (1)

Peter
Peter

Reputation: 333

You can add a <context> to tomcat/conf/server.xml (in this example, linux path):

<Context docBase="/home/yourusername/tomcat/assests" path="/assets" />

If you are using Windows:

<Context docBase="C:\path\to\myapp\assets" path="/assets" />

And then you can access it like any other resource within your webapp (e.g.: /assets/myappConfig.property).

If you are using JDBC for example, you could store the connection properties in a Singleton and request it from there, and that class could take care of change checks on that file.

Upvotes: 1

Related Questions