您的位置:首页 > Web前端 > JavaScript

JSF---->事件处理---动作事件

2012-05-17 23:10 288 查看
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 {

@Override
public 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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: