javascript
JSF----事件处理---动作事件
JSF的事件模型提供一個近似的桌面GUI事件模式,讓熟悉GUI設計的人員也能快速上手Web程序設計。
一、Bean中的方法監聽
如果您需要使用同一個方法來應付多種事件來源,并想要取得事件來源的相關訊息,您可以讓處理事件的方法接收一個javax.faces.event.ActionEvent事件參數,例如:
UserBean.java
package wsz.ncepu;import javax.faces.event.ActionEvent;public class UserBean {private String name;private String password;private String errMessage;private String outcome;public void setName(String name) {this.name = name;}public String getName() {return name;}public void setPassword(String password) {this.password = password;}public String getPassword() {return password;}public void setErrMessage(String errMessage) {this.errMessage = errMessage;}public String getErrMessage() {return errMessage;}public void verify(ActionEvent e) {if(!name.equals("justin") ||!password.equals("123456")) {errMessage = "名稱或密碼錯誤" + e.getSource();outcome = "failure";}else {outcome = "success";}}public String outcome() {return outcome;} }在上例中,我們讓verify方法接收一個ActionEvent對象,當使用者按下按鈕,會自動產生ActionEvent對象代表事件來源,我們故意在錯誤訊息之后如上事件來源的字符串描述,這樣就可以在顯示錯誤訊息時一并顯示事件來源描述。為了提供ActionEvent的存取能力,您的index.jsp可以改寫如下:
index.jsp
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@page contentType="text/html;charset=Big5"%><html><head><title>第一個JSF程序</title></head><body><f:view><h:form><h3>請輸入您的名稱</h3><h:outputText value="#{user.errMessage}"/><p>名稱: <h:inputText value="#{user.name}"/><p>密碼: <h:inputSecret value="#{user.password}"/><p><h:commandButton value="送出"actionListener="#{user.verify}"action="#{user.outcome}"/></h:form></f:view></body></html>主要改變的是按鈕上使用了actionListener屬性,這種方法可以使用一個ActionListener,JSF會先檢查是否有指定的actionListener,然后再檢查是否指定了動作方法并產生預設的ActionListener,并根據其決定action綁定的傳回值,進而導航頁面。
二、通過實現ActionListener接口來實現動作監聽器類
如果您要注冊多個ActionListener,例如當使用者按下按鈕時,順便在記錄文件中增加一些記錄訊息,您可以實javax.faces.event.ActionListener,例如:
LogHandler.java
package wsz.ncepu;import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener;public class LogHandler implements ActionListener {@Overridepublic void processAction(ActionEvent arg0) throws AbortProcessingException {System.out.println("LogHandler is processing!");}}這么一來,您就可以使用<f:actionListener>卷標向組件注冊事件,例如:
<h:commandButton value="送出" action="#{user.outcome}" actionListener="#{user.verify}"><f:actionListener type="wsz.ncepu.LogHandler" /></h:commandButton><f:actionListener>會自動產生type所指定的對象,并呼叫組件的addActionListener()方法注冊Listener。
?
總結
以上是生活随笔為你收集整理的JSF----事件处理---动作事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#键盘事件处理
- 下一篇: gradle idea java ssm