How to set a parameter for a Java Web application

一个人想着一个人 提交于 2020-01-01 08:35:11

问题


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


回答1:


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.




回答2:


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");



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6187296/how-to-set-a-parameter-for-a-java-web-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!