我正在尝试以编程方式创建一个HtmlCommandButton,遵循下面的示例
http://javaevangelist.blogspot.ch/2013/01/jsf-21-tip-of-day-programmatically.html
如果我添加了ajax行为,一切都会正常工作(即调用actionListener ),如果关闭ajax,它就不会工作。
支持bean:
@Named
@RequestScoped
public class CommandBean implements Serializable {
public String generateUUID() {
return java.util.UUID.randomUUID().toString();
}
}解决方案1(使用ajax)
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)
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;
}调用代码:
createCommandButton(FacesContext.getCurrentInstance(),
"#{commandBean.generateUUID()}", "Generate UUID");JSFUtils:
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)来排除验证错误。
https://stackoverflow.com/questions/47589580
复制相似问题