问题
I have a web application using Struts2 with Freemarker templates, and Spring4.
I have a few configuration strings that are stored in a .properties
file which I need to render on every page (for example, our CDN path, which contains a version string). Right now these properties are read by spring and stored in an instance of org.springframework.core.env.Environment
.
Is there an easy way to make my Environment instance accessible to all of my views? We have another application which does this through action inheritance, where a base class has a getEnvironment()
method. I dislike this approach as every action must extend the base class.
回答1:
Put your logic in a bean (eg. Configuration.java) that is then injected (through Spring DI, Java EE CDI, or whatever) in all the actions needing it, and exposed through a Getter.
But I would not underestimate the inheritance approach here, it's not as bad as you're describing it, 'cause you can build your inheritance tree adding specification while traversing it: one BaseAction, some Sub-BaseActions, some sub-sub... etc. Read more.
If you discover later that something you've put on a BaseAction is needed by sibling BaseActions, just move it one level up (in a parent BaseAction, up to the first one, common to everyone).
回答2:
Write an interceptor that will intercept every action and add this interceptor to the custom interceptor stack. This stack you should make a default interceptor stack.
<interceptors>
<interceptor name="myinterceptor" class="com.company.interceptor.MyInterceptor"/>
<interceptor-stack name="customStack">
<interceptor-ref name="myinterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="customStack"/>
In the implementation of myinterceptor
get bean from the application context and put it on the value stack. In every JSP you can access a value stack's object using OGNL.
回答3:
Well, I think the inheritance solution fits well with your problem, all your controllers need these properties, so it is the best and most logical approach.
You could try the interceptor solution like Roman just told you, but I think interceptors are a little tricky to configure and the Struts2 error logs doesn't really help when something goes bad inside interceptors and you have a big application, moreover you would loose performance processing logic at the beggining of every action instead of using it with inheritance.
来源:https://stackoverflow.com/questions/35682125/how-can-i-expose-an-object-to-all-of-my-struts2-views