struts 2 - where should I set global application variables?

久未见 提交于 2019-12-24 13:45:21

问题


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 the 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


回答1:


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.




回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/2730547/struts-2-where-should-i-set-global-application-variables

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