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

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

问题描述

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

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并使用Singleton模式(Singleton类),但是由于范围问题,我无法使其正常工作.

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方式没有什么不同.您可以使用enum s或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 <o:importConstants> .

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天全站免登陆