如何在Struts 2的所有视图中公开对象? [英] How can I expose an object to all of my views in Struts 2?

查看:58
本文介绍了如何在Struts 2的所有视图中公开对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,它使用带有Freemarker模板的Struts 2和Spring 4.

I have a web application using Struts 2 with Freemarker templates, and Spring 4.

我有一些配置字符串存储在 .properties 文件中,我需要在每个页面上进行渲染(例如,我们的CDN路径,其中包含版本字符串).现在,这些属性由Spring读取,并存储在 org.springframework.core.env.Environment 的实例中.

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.

是否有一种简单的方法可以使我的所有视图都可以访问我的 Environment 实例?

Is there an easy way to make my Environment instance accessible to all of my views?

我们还有另一个应用程序,它通过操作继承来执行此操作,其中基类具有 getEnvironment()方法.我不喜欢这种方法,因为每个操作都必须扩展基类.

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.

推荐答案

将您的逻辑放入一个bean(例如Configuration.java)中,然后将其注入(通过Spring DI,Java EE CDI或其他方式)在所有操作中需要它,并通过Getter公开.

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.

但是我不会低估继承方法 在这里 ,它并不像您描述的那样糟糕,因为您可以在遍历的同时构建指定规格的继承树它:一个BaseAction,一些Sub-BaseAction,一些子Sub ...等等.了解更多.

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.

如果以后发现同级BaseAction需要用在BaseAction上的东西,只需将其上移一个级别(在父BaseAction中,向上移动到每个人都通用的第一个).

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).

这篇关于如何在Struts 2的所有视图中公开对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆