JSF 2 actionListener示例

在JSF中,通过单击按钮或链接组件(例如h:commandButtonh:commandLink)来触发“ 动作事件 ”。

动作与动作侦听器
不要混淆这两个标记, 动作用于执行业务逻辑和导航任务; 而动作侦听器用于执行UI界面逻辑或动作调用观察。

此动作侦听器的常见用例用于获取附加到组件的属性值,请参阅此JSF 2 f:attribute示例

这是两种实现方法:

1.方法绑定

在按钮或链接组件中,可以直接在“ actionListener ”属性中指定bean的方法。

JSF页面…

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
     
    <h:body>
    	
    <h1>JSF 2 actionListener example</h1>
		
	<h:form id="form">
			
	  <h:commandButton id="submitButton" 
		value="Submit" action="#{normal.outcome}" 
		actionListener="#{normal.printIt}" />
		
	</h:form>
		
    </h:body>
</html>

托管豆…
与动作事件交互的方法应接受一个ActionEvent参数。

package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
 
@ManagedBean(name="normal")
@SessionScoped
public class NormalBean{

	public String buttonId; 

	public void printIt(ActionEvent event){
		
		//Get submit button id
		buttonId = event.getComponent().getClientId();
		
	}
	
	public String outcome(){
		return "result";
	}
}

2. ActionListener

在按钮或链接组件中,在其中添加“ f:actionListener ”标签,并指定ActionListener接口的实现类,并覆盖其processAction()

JSF页面…

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
     
    <h:body>
    	
    <h1>JSF 2 actionListener example</h1>
		
	<h:form id="form">
		
	  <h:commandButton id="submitButton" 
		value="Submit" action="#{normal.outcome}" >
		<f:actionListener type="com.mkyong.NormalActionListener" />
	  </h:commandButton>
				
	</h:form>
		
    </h:body>
</html>

ActionListener接口的实现

package com.mkyong;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

public class NormalActionListener implements ActionListener{

	@Override
	public void processAction(ActionEvent event)
		throws AbortProcessingException {
		
		System.out.println("Any use case here?");
	
	}
	
}

下载源代码

下载它– JSF-2-ActionListener-Example.zip (10KB)

参考

  1. Stackoverflow –动作和动作监听器
  2. ActionEvent JavaDoc

翻译自: https://mkyong.com/jsf2/jsf-2-actionlistener-example/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值