在 JSF 中有一个“常量"类 [英] Having a "constants"-class in JSF

查看:20
本文介绍了在 JSF 中有一个“常量"类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSF/Primefaces 构建一个 Web 应用程序.我需要一个常量"类,即一个由常量组成的类.这些常量主要是将在整个应用程序中使用的导航命令.我这样做的原因是为了避免临时实例化字符串.

I'm building a web-application using JSF/Primefaces. I need to have a "constants"-class, i.e. a class that will consist of constants. These constants are mainly navigational commands that will be used throughout the application. The reason I am doing this is to avoid having instantiated Strings on an ad-hoc basis.

我如何实现这一点,使常量可以从支持 bean 和 XHTML 文件中访问?

How do I achieve this, making the constants accessible from both backing beans and XHTML files?

我曾尝试使用 @ApplicationScoped 并使用单例模式(单例类),但由于范围问题,我无法使其正常工作.

I have tried using @ApplicationScoped and using the Singleton-pattern (Singleton class) but I am unable to get it working due to scope issues.

也许我只是使用了错误的方法.欢迎任何想法/建议.

Or maybe I am just using the wrong approach. Any ideas/suggestions are welcome.

推荐答案

如何实现这一点,使常量可以从支持 bean 和 XHTML 文件访问?

在支持 bean 方面,这显然很容易.由于它们只是 Java 类,因此它与普通"Java 方式没有什么不同.您可以使用 enums 或 public static final 字段.在视图中,这是一个不同的故事.在即将到来的 3.0 版本之前,EL 不以任何方式支持常量.

In backing beans, it's obviously easy. As they're just Java classes, it's not different from the "normal" Java way. You could use enums or public static final fields. In views, this is a different story. Until the upcoming version 3.0, EL does namely not support constants in any way.

我建议使用枚举,因为 EL 在字符串比较中隐式支持它们.它不进行任何编译时/运行时类型安全检查,但您可以将枚举名称用作字符串.例如

I'd suggest using enums as EL has implicit support for them in string comparisons. It does not do any compiletime/runtime type safety checks, but you can use the enum name as a string. E.g.

<h:someComponent ... rendered="#{order.status == 'SHIPPING'}" />

如果您更喜欢更多的自我记录代码和运行时检查(不,编译时检查是不可能的),那么您可以考虑使用 OmniFaces .

If you prefer more self documenting code and a runtime check (no, a compiletime check is not possible), then you could consider using OmniFaces <o:importConstants>.

<o:importConstants type="com.example.OrderStatus" />
<h:someComponent ... rendered="#{order.status == OrderStatus.SHIPPING}" />

这只是 IMO 有点笨拙.然而,运行时检查在开发过程中很好.一个错字很容易被发现.

This is IMO only a bit more clumsy. The runtime check is however nice during development. A typo is easily overseen.

在即将发布的 EL 3.0(JSR-341,Java 的一部分EE 7),可以用同样的方式引用常量.另请参阅如何在 EL 中引用常量?这只需要常量的编程导入,因为没有标准的 JSP/Facelets 标记.

In the upcoming EL 3.0 (JSR-341, part of Java EE 7), it's possible to reference constants the same way. See also How to reference constants in EL? This only requires programmatic import of the constants as there's no standard JSP/Facelets tag for that.

这篇关于在 JSF 中有一个“常量"类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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