如何在JSF中创建切换按钮? [英] How can I create toggle buttons in JSF?

查看:74
本文介绍了如何在JSF中创建切换按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JSF中创建切换按钮?

How can I create toggle buttons in JSF?

基本上,我需要两个按钮"in"和"out".它们本质上调用了相同的托管bean,但由于每次单击,都应禁用一个单击,而应启用另一个单击,反之亦然.如何才能做到这一点?我应该使用ajax功能吗?

Basically, I need two buttons "in" and "out". They essentially call the same managed bean, but as a result of every click the one should be disabled and the other should be enabled and vice versa. How can this be done? Should I use ajax functionality?

推荐答案

只有一个boolean属性,您可以在操作方法中将其取反,然后在两个按钮的disabled属性中取反使用该属性.

Just have a boolean property which you inverse in action method and use exactly that property in the disabled attribute of the both buttons, inversed.

开球示例:

@ManagedBean
@ViewScoped
public class Bean {

    private boolean enabled;

    public void toggle() {
        enabled = !enabled;
    }

    public boolean isEnabled() {
        return enabled;
    }

}

使用

<h:form>
    <h:commandButton value="Enable" action="#{bean.toggle}" disabled="#{bean.enabled}" />
    <h:commandButton value="Disable" action="#{bean.toggle}" disabled="#{not bean.enabled}" />
</h:form>

从技术上讲,Ajax是不必要的.可以随意在两个按钮上添加<f:ajax>来改善用户体验.

Ajax is technically not necessary. Feel free to add <f:ajax> to both buttons to improve the user experience though.

反过来,非常需要@ViewScoped bean.一个@RequestScoped会在请求结束时被丢弃,并在下一个请求中重新创建,从而导致boolean被重新初始化为默认值,因此在第二次单击后似乎无法工作,因为JSF将作为防范篡改/被黑客攻击的一部分.请求还会在实际调用操作之前检查disabled(和rendered)属性.

A @ViewScoped bean is in turn very necessary. A @RequestScoped one would be trashed on end of request and recreated in next request, hereby causing the boolean to be reinitialized to default and thus seemingly fail to work after second click, because JSF will as part of safeguard against tampered/hacked requests also check the disabled (and rendered) attribute before actually invoking the action.

  • How to choose the right bean scope?
  • commandButton/commandLink/ajax action/listener method not invoked or input value not updated (point 5)

这篇关于如何在JSF中创建切换按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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