首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSF编程方式-如果关闭HtmlCommandButton,则不会调用Bean方法

JSF编程方式-如果关闭HtmlCommandButton,则不会调用Bean方法
EN

Stack Overflow用户
提问于 2017-12-01 16:45:44
回答 0查看 401关注 0票数 1

我正在尝试以编程方式创建一个HtmlCommandButton,遵循下面的示例

http://javaevangelist.blogspot.ch/2013/01/jsf-21-tip-of-day-programmatically.html

如果我添加了ajax行为,一切都会正常工作(即调用actionListener ),如果关闭ajax,它就不会工作。

支持bean:

代码语言:javascript
复制
@Named
@RequestScoped
public class CommandBean implements Serializable {

   public String generateUUID() {
        return java.util.UUID.randomUUID().toString();
    }
}

解决方案1(使用ajax)

代码语言:javascript
复制
private HtmlCommandButton createCommandButtonWithAjax(final FacesContext context,
        final String methodExpression, final String value) {

    Application application = context.getApplication();
    Class<?>[] clazz = new Class<?>[]{};
    HtmlCommandButton htmlCommandButton =
            (HtmlCommandButton) application.createComponent(HtmlCommandButton.COMPONENT_TYPE);
    htmlCommandButton.setValue(value);

    AjaxBehavior ajaxBehavior = (AjaxBehavior) FacesContext.getCurrentInstance().getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
    ((UIComponentBase)htmlCommandButton).addClientBehavior("click", ajaxBehavior);

MethodExpression actionListener = application.getExpressionFactory().createMethodExpression(FacesContext.getCurrentInstance().getELContext(), action, String.class, clazz);
button.addActionListener(new MethodExpressionActionListener(actionListener));

    return htmlCommandButton;
}

解决方案2(无ajax)

代码语言:javascript
复制
private HtmlCommandButton createCommandButton(final FacesContext context,
        final String methodExpression, final String value) {
    Application application = context.getApplication();
    Class<?>[] clazz = new Class<?>[]{};
    HtmlCommandButton htmlCommandButton =
            (HtmlCommandButton) application.createComponent(HtmlCommandButton.COMPONENT_TYPE);
    htmlCommandButton.setValue(value);
    htmlCommandButton.setActionExpression(JSFUtils.createMethodExpression(methodExpression, String.class, clazz));
    return htmlCommandButton;
}

调用代码:

代码语言:javascript
复制
createCommandButton(FacesContext.getCurrentInstance(),
                "#{commandBean.generateUUID()}", "Generate UUID");

JSFUtils:

代码语言:javascript
复制
  public static MethodExpression createMethodExpression(String methodExpression,Class<?> expectedReturnType,Class<?>[] expectedParamTypes) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory()
            .createMethodExpression(context.getELContext(), methodExpression, expectedReturnType, expectedParamTypes);
  }

解决方案1有效,解决方案2无效:未调用bean方法generateUUID()。我也尝试过使用htmlCommandButton.setImmediate(true)来排除验证错误。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47589580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档