JSF事件监听器–动作,阶段,值更改

本文详细介绍了JSF(JavaServer Faces)中的事件和监听器模型,包括JSF事件类、JSF侦听器类、JSF活动、JSF价值变更事件及JSF阶段事件。通过具体实例展示了如何在JSF项目中实现和使用这些事件和监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSF Event and Listener model is based on the JavaBeans specification. An event is defined as a signal triggered based upon the user actions such as click of button, hyperlink, changing the input value etc. JSF tells the component to invoke the appropriate listener class that process the event generated by the user.

JSF事件和侦听器模型基于JavaBeans规范。 事件定义为基于用户操作(例如单击按钮,超链接,更改输入值等)触发的信号。JSF告诉组件调用处理用户生成的事件的适当侦听器类。

Lets now look in detail about the event classes and listener interfaces.

现在让我们详细了解事件类和侦听器接口。

JSF事件类 (JSF Event Classes)

The classes related to the JSF events are defined in the javax.faces.event package. While implementing the event classes in JSF, the javax.faces.event package has to be extended. The generated event can be obtained by calling event.getComponent as

与JSF事件相关的类在javax.faces.event包中定义。 在JSF中实现事件类时,必须扩展javax.faces.event包。 可以通过将event.getComponent调用为

UIComponent ui = new UIComponent();
MyFacesEvent ev1 = new MyFacesEvent(ui); 
UIComponent sc1 = ev1.getComponent();

The events can be queued at the end of request processing lifecycle by using the queue() method. The queuing at a particular stage can be done by using the following code

可以使用queue()方法在请求处理生命周期结束时将事件排队。 可以使用以下代码在特定阶段进行排队

MyFacesEvent ev1 = new MyFacesEvent();
ev1.setPhaseId(PhaseId.PROCESS_VALIDATIONS);

In the above code, the events will occur at the end of the process validation phase.

在上面的代码中,事件将在流程验证阶段结束时发生。

JSF侦听器类 (JSF Listener Classes)

An event is associated with the listener class for all the events. For instance, if the event is a valuechange event then the corresponding listener class ValueChangeListener is associated with it. SImilarly the ActionListener is for the action event.

事件与所有事件的侦听器类相关联。 例如,如果该事件是valuechange事件,则将相应的侦听器类ValueChangeListener与之关联。 类似地, ActionListener用于动作事件。

JavaBeans specifications makes the methods mandatory for registering a particular listener to an event. For example if the event name is MyOwnEvent and the Listener class is MyOwnListener and want this event to be called on MyOwnComponent then the following methods have to be defined for registering the listener class.

JavaBeans规范使方法成为注册事件的特定侦听器的必需方法。 例如,如果事件名称为MyOwnEvent且侦听器类为MyOwnListener并希望在MyOwnComponent上调用此事件,则必须定义以下方法来注册侦听器类。

public void addMyOwnComponentListener(MyOwnListener l1)

public void removeMyOwnListener(MyOwnListener l1)

public void MyOwnListener[] getMyOwnListeners()

JSF活动 (JSF Events)

The JSF events fall into one of the three categories namely

JSF事件属于以下三类之一:

  1. Action Events

    动作事件
  2. Value Change Events

    价值变化事件
  3. Phase Events

    阶段事件

JSF动作事件 (JSF Action Events)

Action events are the events that are generated for the ui components like command button or command hyperlink. Any number of listeners can be attached to a single event.

动作事件是为ui组件(如命令按钮或命令超链接)生成的事件。 一个事件可以附加任意数量的侦听器。

Consider an example of submitting a form.

考虑提交表单的示例。

Create a JSF view page mobile.xhtml as shown below.

如下所示创建一个JSF视图页面mobile.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html">
<h:head>
	<title>Text fields</title>
</h:head>
<h:body>
	<h3>Mobile details</h3>
	<h:form>
		<h:panelGrid columns="3">
			<h:outputLabel for="mname">Company Name:</h:outputLabel>
			<h:inputText id="mname"></h:inputText>
			<br />
			<br />

			<h:outputLabel for="model">Model Number:</h:outputLabel>
			<h:inputText id="model"></h:inputText>
			<br />
			<br />
			<h:outputLabel for="color">Color:</h:outputLabel>
			<h:inputText id="color"></h:inputText>
			<br />
			<br />
			<h:commandButton value="Mobile Action Listener"
				actionListener="#{mobileActionListener.processAction}" />

		</h:panelGrid>
	</h:form>
</h:body>
</html>

Here we define attribute actionListener calling the method processAction of MobileActionListener class.

在这里,我们定义属性actionListener调用MobileActionListener类的processAction方法。

Create MobileActionListener.java class as;

创建MobileActionListener.java类为;

package com.journaldev.jsf.beans;

import javax.faces.FactoryFinder;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;

@ManagedBean
@SessionScoped
public class MobileActionListener implements ActionListener {

	public MobileActionListener() {
	}

	@Override
	public void processAction(ActionEvent ae) throws AbortProcessingException {

		UIComponent ui = ae.getComponent();

		System.out.println("Event source is" + ui.getClass().getName());

	}

	public void listAllPhaseListeners() {
		LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
				.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
		Lifecycle applicationLifecycle = lifecycleFactory
				.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

		PhaseListener phaseListeners[] = applicationLifecycle
				.getPhaseListeners();
		for (PhaseListener phaseListener : phaseListeners) {
			System.out.println(phaseListener.getPhaseId());
		}
	}

}

Here we implement the ActionListener class and override the processAction method. Inside this method we are just printing the event that is invoked by the user. The ui.getClass().getName() methods prints the action event triggered.

在这里,我们实现ActionListener类并覆盖processAction方法。 在此方法内部,我们仅打印由用户调用的事件。 ui.getClass().getName()方法输出触发的动作事件。

Make the following entry in faces-config.xml file to invoke the actionlistener class.

faces-config.xml文件中进行以下输入,以调用actionlistener类。

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
              xmlns="https://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

    <managed-bean>
	    <managed-bean-name>mobileActionListener</managed-bean-name>
	        <managed-bean-class>
	            com.journaldev.jsf.beans.MobileActionListener
	        </managed-bean-class>
	    <managed-bean-scope>request</managed-bean-scope>
	</managed-bean>

    
    <lifecycle>
    <phase-listener>
        com.journaldev.jsf.beans.CustomPhaseListener
    </phase-listener>
    
</lifecycle>
</faces-config>

The managed bean Mobile Action Listener class path is specified in the faces-config.xml file.

受管Bean Mobile Action Listener类路径在faces-config.xml文件中指定。

Now run the application and go to the mobile.xhtml page in browser and click the submit button which produces the following output in the console

现在运行该应用程序,并在浏览器中转到mobile.xhtml页面,然后单击提交按钮,这将在控制台中产生以下输出

Event source is javax.faces.component.html.HtmlCommandButton

Since the submit button is the event fired the event is CommandButton tag which corresponds to submit button.

由于提交按钮是触发的事件,因此该事件是CommandButton标记,与提交按钮相对应。

JSF价值变更事件 (JSF Value Change Event)

Value change events refers to the UI components textfield, radio button, list box etc. The value change event will get fired as soon as the value is changed in the UI component. Listeners for this event usually perform validations on the fields to check whether the entered value is valid or not according to the requirements.

值更改事件是指UI组件的文本字段,单选按钮,列表框等。值更改事件将在UI组件中更改后立即触发。 此事件的侦听器通常根据要求在字段上执行验证,以检查输入的值是否有效。

Consider the following example of changing a value in a listbox and displaying the new value

考虑下面的示例,该示例在列表框中更改值并显示新值

Create mobilevalue.xhtml as;

创建mobilevalue.xhtml为;

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core">
<h:head>
	<title>Value Change Event</title>
</h:head>
<h:body>
	<h3>Value Change Event Example</h3>
	<h:form>
		<h:panelGrid columns="3">

			<h:selectOneMenu id="name" value="#{mobileValueChangeListener.name}"
				onchange="submit()"
				valueChangeListener="#{mobileValueChangeListener.onSelectNames}">
				<f:selectItem itemValue="Nokia" itemLabel="Nokia" />
				<f:selectItem itemValue="Samsung" itemLabel="Samsung" />
				<f:selectItem itemValue="Blackberry" itemLabel="Blackberry" />
				<f:selectItem itemValue="Sony" itemLabel="Sony" />
				<f:selectItem itemValue="Mi3" itemLabel="Mi3" />

			</h:selectOneMenu>

		</h:panelGrid>
	</h:form>
	<br />
	<br />
	<h:outputText value="#{mobileValueChangeListener.result}"></h:outputText>
</h:body>
</html>

Here we invoke the valueChangeListener attribute and invoke the onSelectNames method of the MobileValueChangeListener bean.

在这里,我们调用valueChangeListener属性,并调用MobileValueChangeListener bean的onSelectNames方法。

Create the MobileValueChangeListener.java bean as;

创建MobileValueChangeListener.java bean为;

package com.journaldev.jsf.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;

@ManagedBean
@SessionScoped
public class MobileValueChangeListener {

	private String name;
	private String result;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public MobileValueChangeListener() {
	}

	public void onSelectNames(ValueChangeEvent vc) {

		Object oval = vc.getOldValue();
		Object nval = vc.getNewValue();

		System.out.println("oval" + oval);
		System.out.println("nval" + nval);

		if (nval != null) {
			result = "Newly changed value is:" + (String) nval;

		}
	}

}

In the onSelectNames method we obtain the new value and old value through the getOldValue and getNewValue methods and check if the new value is not equal null and if true store the new value to the result variable and display the value of this variable on the JSF view page.

在onSelectNames方法中,我们通过getOldValue和getNewValue方法获取新值和旧值,并检查新值是否不等于null,如果为true,则将新值存储到结果变量中,并在JSF视图上显示此变量的值。页。

Now run the application that produces the following output on changing the value in the listbox.

现在,运行在更改列表框中的值时产生以下输出的应用程序。

JSF阶段事件 (JSF Phase Event)

This type of event involves the events to be fired in one of the six phases of JSF lifecycle either during start or towards the end of each phase.

这种类型的事件涉及在每个阶段的开始或结束时在JSF生命周期的六个阶段之一中触发的事件。

Consider an example of capturing the phase events by creating CustomPhaseListener.java as;

考虑一个通过创建CustomPhaseListener.java来捕获阶段事件的CustomPhaseListener.java

package com.journaldev.jsf.beans;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class CustomPhaseListener implements PhaseListener {

	private static final long serialVersionUID = -1395570878923714114L;

	@Override
	public void afterPhase(PhaseEvent pe) {
		System.out.println("After phase" + pe.getPhaseId());
	}

	@Override
	public void beforePhase(PhaseEvent pe) {

		System.out.println("Before phase" + pe.getPhaseId());
	}

	@Override
	public PhaseId getPhaseId() {

		return PhaseId.ANY_PHASE;
	}

}

Create a JSF view page phaseListener.xhtml as;

创建一个JSF视图页面phaseListener.xhtml作为;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:h="https://java.sun.com/jsf/html">

<h:head>
	<title>Phase Listener example</title>
</h:head>
<h:body>
	<h3>Phase Listener example</h3>
	<h:form>
		<h:inputText id="mname" />

		<h:commandButton id="button" value="Submit" />

		<h:messages />

	</h:form>
</h:body>
</html>

Now run the application and enter some text on phaseListener page and click the submit button. Check the server logs and following output is produced.

现在运行该应用程序,并在phaseListener页面上输入一些文本,然后单击Submit按钮。 检查服务器日志,并产生以下输出。

Before phase RESTORE_VIEW 1
After phase RESTORE_VIEW 1
Before phase APPLY_REQUEST_VALUES 2
After phase APPLY_REQUEST_VALUES 2
Before phase PROCESS_VALIDATIONS 3
After phase PROCESS_VALIDATIONS 3
Before phase UPDATE_MODEL_VALUES 4
After phase UPDATE_MODEL_VALUES 4
Before phase INVOKE_APPLICATION 5
After phase INVOKE_APPLICATION 5
Before phase RENDER_RESPONSE 6
After phase RENDER_RESPONSE 6

The event id’s for each phase is printed in the console.

每个阶段的事件ID都打印在控制台中。

Finally below image shows the project structure.

JSF Event

最后,下图显示了项目结构。

You can download the final project from below link and play around with it to learn more about JSF Event and Listeners.

您可以从下面的链接下载最终项目并进行试用,以了解有关JSF Event和Listeners的更多信息。

翻译自: https://www.journaldev.com/7028/jsf-event-listener-action-phase-value-change

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值