struts 2 - where should I set global application variables?
I'm using struts 2 and I'd like to read some custom-defined parameters (global variables), preferably from web.xml or some custom ".properties" file (i.e. not hardcoded in the Java sources). This problem has been driving me mad for t开发者_StackOverflowhe past half hour as I can't google any reasonable solution.
What is the best way to do this? I find it strange that it is so difficult ...
all the best
Nicola Montecchio
There are a few ways to do this.
- Constants can be set in struts.xml (http://struts.apache.org/2.x/docs/constant-configuration.html).
- If you're using Spring along with Struts 2 you should be able to set some parameters in your applicationContext.xml.
- You might also consider using JNDI properties, in a configuration file specific to each application server deployment (http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html)
Ask yourself first: are those constants really pertinent to Struts2 or just to your application ?
If the later, this is not really a Struts2 question, and you -trust me- dont' want tie you "constants" management to Struts2 (or web.xml), they should be accesible from your application code outside the webapp (for example, from some testing code).
I understand that you feel bad about "harcoding" constants in some (say) Constants class (with static final fields), but be aware that this might not be so bad practice -if they are really constants, unlikely to be changed independently of your java code. Worth a thought.
If not, you might need some ConstantsManager class, which might be a singleton stateless object (or some kind of 'Service' object), which knows how to load the constants, for example from some property file in the classpath. How do the objects of your application (including perhaps some Struts2 action) get a reference to that ConstantsManager instance? In the simplest (and dirtiest) implementation, you'd have a Singleton pattern implementation with a static getInstance() method. More flexible and fashionable is the DI/IOC way, perhaps with some beans container, as Spring; and Struts2 is well suited to play with that. And if you're not familiar with this concepts, they will surely pop up soon, for issues similiar (but less trivial) that accessing some constants.
I don't know if this works but http://struts.apache.org/2.0.6/struts2-core/apidocs/com/opensymphony/xwork2/ActionContext.html#get%28java.lang.Object%29
ActionContext.getContext().get(...) might work.
精彩评论