h:button和h:commandButton之间的区别

Gee*_*eek 69 jsf button jsf-2

在JSF 2中,h:button和之间有什么区别h:commandButton

Bal*_*usC 106

<h:button>

<h:button>生成一个HTML <input type="button">.生成的元素使用JavaScript outcome使用HTTP GET请求导航到属性给出的页面.

例如

<h:button value="GET button" outcome="otherpage" />
Run Code Online (Sandbox Code Playgroud)

会产生

<input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" />
Run Code Online (Sandbox Code Playgroud)

即使这最终导致浏览器地址栏中的(可收藏的)URL更改,这也不是SEO友好的.Searchbots不会关注中的网址onclick.你最好使用一个<h:outputLink>或者<h:link>如果SEO在给定的URL上很重要.如果需要,您可以在生成的HTML <a>元素上放入一些CSS ,使其看起来像一个按钮.

请注意,虽然您可以在outcome属性中引用EL表达式,如下所示,

<h:button value="GET button" outcome="#{bean.getOutcome()}" />
Run Code Online (Sandbox Code Playgroud)

单击按钮时不会调用它.相反,当包含按钮的页面仅为了获得要嵌入到生成的onclick代码中的导航结果而呈现时,它已被调用.如果您曾试图使用动作方法语法outcome="#{bean.action}",那么您可能会因为这个错误/误解而面临javax.el.E​​LException:在com.example.Bean类中找不到属性actionMethod.

如果您打算根据POST请求调用方法<h:commandButton>,请改用,请参阅下文.或者,如果您打算作为GET请求的结果调用方法,请转到页面加载时调用JSF托管bean操作,或者如果您还有GET请求参数<f:param>,如何在页面加载时处理支持bean中的GET查询字符串URL参数?


<h:commandButton>

所述<h:commandButton>产生一HTML <input type="submit">按钮其默认提交的父<h:form>使用HTTP POST方法并调用附接至操作action,actionListener和/或<f:ajax listener>,如果有的话.这<h:form>是必需的.

例如

<h:form id="form">
    <h:commandButton id="button" value="POST button" action="otherpage" />
</h:form>
Run Code Online (Sandbox Code Playgroud)

会产生

<form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="form" value="form" />
    <input type="submit" name="form:button" value="POST button" />
    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" />
</form>
Run Code Online (Sandbox Code Playgroud)

请注意,它因此提交到当前页面(表单操作URL将显示在浏览器地址栏中).之后它将转发到目标页面,而不会对浏览器地址栏中的URL进行任何更改.您可以?faces-redirect=true在结果值中添加参数以在POST后触发重定向(根据Post-Redirect-Get模式),以便目标URL变为可收藏.

<h:commandButton>通常专门用于提交一个POST形式,不执行页到页面导航.通常,action指向某些业务操作,例如在DB中保存表单数据,这会返回String结果.

<h:commandButton ... action="#{bean.save}" />
Run Code Online (Sandbox Code Playgroud)

public String save() {
    // ...
    return "otherpage";
}
Run Code Online (Sandbox Code Playgroud)

返回nullvoid将带您回到相同的视图.还返回一个空字符串,但它会重新创建任何视图范围的bean.现在,使用现代JSF2,并且<f:ajax>通常操作只返回到相同的视图(因此,nullvoid),其中结果由ajax有条件地呈现.

public void save() {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 那些实际上是无关的.`<h:form>`将**始终**生成一个指向当前请求的URL的`<form action>`.`<h:commandButton action ="otherpage">`基本上指示JSF在POST请求完成时执行转发到给定的视图ID. (3认同)
  • Searchbots通常只解释HTML并忽略JS(和CSS).虽然谷歌正在尝试破译JS代码.您应该将searchbots视为已禁用JS的用户. (2认同)

dsg*_*fin 6

h:button- 点击h:button发出可收藏的GET请求.

h:commandbutton- h:commandbutton发出POST请求而不是get请求,该请求将表单数据发送回服务器.


归档时间:

查看次数:

111287 次

最近记录:

7 年 前