java 如何使用 JSF 和 Facelets 实现一些 if-then 逻辑?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3398388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement some if-then logic with JSF and Facelets?
提问by Roman
I have a bean with field status. Depending on statusvalue different css class should be applied to render it.
我有一个带字段的豆子status。应根据status值应用不同的 css 类来呈现它。
So, I need something like this (very far from real things pseudocode):
所以,我需要这样的东西(与真实的伪代码相去甚远):
if status == "Approved"
cssClass = "green"
if status == "Rejected"
cssClass = "red"
<span class="cssClass">Some info</span>
I tried to apply jstlbut I can't make it work with facelets and jsf (but I heard that it is possible, maybe its truth). Here is the code:
我试图申请,jstl但我不能让它与 facelets 和 jsf 一起工作(但我听说这是可能的,也许是事实)。这是代码:
<c:choose>
<c:when test="#{report.approved}">
<c:set var="statusClass" value="approved"/>
</c:when>
<c:when test="#{report.rejected}">
<c:set var="statusClass" value="rejected"/>
</c:when>
<c:when test="#{report.inProgress}">
<c:set var="statusClass" value="progress"/>
</c:when>
<c:when test="#{report.pendingHR}">
<c:set var="statusClass" value="pending"/>
</c:when>
</c:choose>
<span class="status ${statusClass}">#{report.formattedStatus}</span>
How should it be done with JSF/Facelets?
应该如何使用 JSF/Facelets 来完成?
回答by BalusC
To give the both sides (model and view) the benefit, rather make use of an enuminstead of four independent booleans which might after all only lead to maintenance trouble.
为了给双方(模型和视图)带来好处,而是使用一个enum而不是四个独立的布尔值,这毕竟可能只会导致维护麻烦。
public enum Status {
APPROVED, REJECTED, PROGRESS, PENDING;
}
It is not only much easier and cleaner to handle in Java side, but you can also just print it in EL.
在 Java 端处理不仅更容易和更清晰,而且您还可以在 EL 中打印它。
<span class="#{bean.status}" />
回答by Thorbj?rn Ravn Andersen
The JSF approach is typically using the renderedattribute on the h-tags. Also note that the EL (expression language) is quite expressive in JSF so you can use ?:in your class expression. E.g.
JSF 方法通常使用renderedh 标签上的属性。另请注意,EL(表达式语言)在 JSF 中非常具有表现力,因此您可以?:在类表达式中使用。例如
<span class="status #{report.approved ? 'approved' : report.rejected ? 'rejected' : report.inProgress ? 'progress' : report.pendingHR ? 'pending' : ''}">
回答by ewernli
Just make cssStatusa properties in the backing bean that is resolved to the correct CSS class.
只需cssStatus在解析为正确 CSS 类的支持 bean 中创建一个属性。
public String getCssStatus() {
if( this.status == .... )
return "green";
else
...
}
And then
接着
<span class="status #{report.cssStatus}">#{report.formattedStatus}</span>
AFAIK, this should work.
AFAIK,这应该有效。

