Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

java - Having a "constants"-class in JSF

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.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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'}" />

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}" />

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...