在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.ELException:在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)
返回null
或void
将带您回到相同的视图.还返回一个空字符串,但它会重新创建任何视图范围的bean.现在,使用现代JSF2,并且<f:ajax>
通常操作只返回到相同的视图(因此,null
或void
),其中结果由ajax有条件地呈现.
public void save() {
// ...
}
Run Code Online (Sandbox Code Playgroud)
h:button
- 点击h:button
发出可收藏的GET
请求.
h:commandbutton
- h:commandbutton
发出POST请求而不是get请求,该请求将表单数据发送回服务器.
归档时间: |
|
查看次数: |
111287 次 |
最近记录: |