在JSF 2.0中, <h:button />和<h:commandButton />标记都用于呈现button类型的HTML输入元素,并使用不同的机制来处理导航。
1. JSF h:commandButton示例
自从JSF 1.x以来,“ h:commandButton ”标记已发布,您可以声明bean,该bean在“ action ”属性中返回导航结果。 如果禁用了JavaScript的浏览器,则导航仍然有效,因为导航是通过表单发布处理的。
1.提交按钮
//JSF
<h:commandButton value="submit" type="submit" action="#{user.goLoginPage}" />
//HTML output
<input type="submit" name="xxx" value="submit" />
2.重置按钮
//JSF
<h:commandButton value="reset" type="reset" />
//HTML output
<input type="reset" name="xxx" value="reset" />
3.普通按钮
//JSF
<h:commandButton value="button" type="button" />
//HTML output
<input type="button" name="xxx" value="button" />
4.带有onclick事件的普通按钮
//JSF
<h:commandButton value="Click Me" type="button" onclick="alert('h:commandButton');" />
//HTML output
<input type="button" name="xxx" value="Click Me" onclick="alert('h:commandButton');" />
2. JSF h:button示例
“ h:button ”是JSF 2.0中的一个新标记,您可以直接在“ result ”属性中声明导航结果,而无需调用Bean来返回上面的“ h:commandButton”之类的结果。 但是,如果禁用了JavaScript的浏览器,则导航将失败,因为“ h:button ”标签会生成一个“ onclick”事件,以通过“ window.location.href”处理导航。 看例子:
1.正常按钮无结果
//JSF
<h:button value="buton" />
//HTML output
<input type="button"
onclick="window.location.href='/JavaServerFaces/faces/currentpage.xhtml; return false;"
value="buton" />
PS:如果省略了result属性,则当前页面URL将被视为结果。
2.带有结果的普通按钮
//JSF
<h:button value="buton" outcome="login" />
//HTML output
<input type="button"
onclick="window.location.href='/JavaServerFaces/faces/login.xhtml; return false;"
value="buton" />
3.带有JavaScript的普通按钮。
//JSF
<h:button value="Click Me" onclick="alert('h:button');" />
//HTML output
<input type="button"
onclick="alert('h:button');window.location.href='/JavaServerFaces/faces/page.xhtml;return false;"
value="Click Me" />
我的想法…
不太确定为什么JSF 2.0发布了这个“ h:button ”标签,JavaScript重定向不切实际,尤其是在禁用JavaScript的浏览器中。 最好的方法是将“ result ”属性集成到“ h:commandButton ”标签中,希望可以在将来的版本中完成。
下载源代码
下载它– JSF-2-Button-CommandButton-Example.zip (10KB)
参考
翻译自: https://mkyong.com/jsf2/jsf-2-button-and-commandbutton-example/