开发者

How to set a parameter for a Java Web application

I have a web app in Java, which uses some external program (invokes a command line tool).

I want to make the path of the command line program configurable, so that I can change it without re-building my application.

Questions:

1) Which exactly parameter should I use (out of those available in web.xml), if it is set only once (at deployment) and thereafter never changes?

2) How can开发者_开发知识库 I access this parameter inside my Java code?

Thanks in advance

Dmitri


web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
  <context-param>
    <param-name>command</param-name>
    <param-value>SOME_COMMAND</param-value>
  </context-param>
.
.
.
.
</web-app>

Java code

String commandToExecute =  getServletContext().getInitParameter("command");

Alternatively

You can also put this thing in property/xml file in the classpath read it and put it to servlet context when context initializes.


You may use an env-entry:

<env-entry>
    <description>command line</descriptor>
    <env-entry-name>commandLine</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>some_command</env-entry-value>
</env-entry>

And get it from anywhere in your webapp code:

javax.naming.Context ctx = new javax.naming.InitialContext();
String command = (String) ctx.lookup("java:comp/env/commandLine");


I would go with a system property in this scenario. Just run your application server with a JVM flag like -Dyour.command.path=/path/to/your/command and then in the code, you just need to write:

String cmd = System.getProperty("your.command.path", "/some/default/fallback/path/cmd");

This way you won't rely on running in some Java EE / servlet container.


It's a two part solution.

  1. First we can make a properties file that is accessible for the web application. This need not be your standard message properties, but a secondary file.
  2. Second your deployment script and your build script can do some extra work to create context directories in the application server where it can copy the properties file from the build and make it available for the command line tools also.

Apache CLI is a very good alternative to do some programmatic access.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜