JSF入门十五(动作事件)

JSF的事件模型提供一个近似的桌面GUI事件方式,让熟悉GUI设计的人员也能快速上手Web程序设计。

 

如果您需要使用同一个方法来应付多种事件来源,并想要取得事件来源的相关信息,您可以让处理事件的方法接收一个javax.faces.event.ActionEvent事件参数,例如:UserBean.java

package bruce.zhao;
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可以改写如下:

<%@ 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,并根据其传回值导航页面。
如果您要注册多个ActionListener,例如当使用者按下按钮时,顺便在记录文件中增加一些记录信息,您可以实现javax.faces.event.ActionListener,例如:LogHandler.java

package bruce.zhao;
import javax.faces.event.ActionListener;
....
public class LogHandler implements ActionListener {
public void processAction(ActionEvent e) {
// 处理Log
}
}

 VerifyHandler.java

package bruce.zhao;
import javax.faces.event.ActionListener;
....
public class VerifyHandler implements ActionListener {
public void processAction(ActionEvent e) {
// 处理验证
}
}

 这么一来,您就可以使用<f:actionListener>标签向组件注册事件,例如:

<h:commandButton value="送出" action="#{user.outcome}">
<f:actionListener type="bruce.zhao.LogHandler"/>
<f:actionListener type="bruce.zhao.VerifyHandler"/>
</h:commandButton>

 <f:actionListener>会自动产生type所指定的对象,并呼叫组件的addActionListener()方法注册Listener。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值