JSF事件处理
【IT168技术文档】
值变化事件
Web应用程序中的组件通常是相互依赖的。可以使得所依赖的组件与值变化事件保持同步。例如,下图显示的应用程序,当选择下拉框中的内容时,在下面显示所选中的内容。这在验证了新值和提交关闭之后由输入组件触发。

上图显示的应用程序将一个值变化监听器连接到select菜单,并使用onchange属性来在菜单值变化之后强迫执行表单提交:
当用户从菜单中选择一个国家时,JavaScript submit函数将被调用来提交菜单的表单,然后它调用JSF生命周期。在处理验证阶段,JSF实现将调用form bean的myEvent()方法。这个方法将根据新的selectedContent值来更改视图的场所:<h:selectOneMenu id="select" valueChangeListener="#{user.myEvent}" onchange="submit();"
value="#{user.selectedContent}">
<f:selectItems value="#{user.countryItems}"></f:selectItems>
</h:selectOneMenu>
/**//*
* Copyright (c) 2006,Science And Technology Of NCEPU
* All rights reserved.
*
* FileName:filename
* Description:description of the file
*
* Version:1.0
* Author:gmplayer
* FinishDate:2007-3-29
*
* http://www.ncepu.edu.cn
*/
package jsf;
![]()
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
![]()
public class UserBean ...{
String result;
String input;
![]()
private ArrayList countryItems = null;
private String selectedContent = null;
![]()
public String getSelectedContent() ...{
return selectedContent;
}
![]()
public void setSelectedContent(String selectedContent) ...{ //保持下拉框的状态不改变
this.selectedContent = selectedContent;
}
![]()
public String getResult() ...{
return result;
}
public void setResult(String result) ...{
this.result = result;
}
![]()
public void listen(ActionEvent e) ...{ //按钮点击时触发的事件
FacesContext context = FacesContext.getCurrentInstance();
String myclientId = e.getComponent().getClientId(context);
String clientId = e.getComponent().getId();
if (clientId.equals("btnSubmitAdd"))
setResult(getInput());
}
![]()
public void myEvent(ValueChangeEvent e) ...{ //下拉框改变时触发的事件
FacesContext context = FacesContext.getCurrentInstance();
String clientId = e.getComponent().getId();
if (clientId.equals("select")) ...{
setResult(e.getNewValue().toString());
![]()
}
}
![]()
public String getInput() ...{
return input;
}
public void setInput(String input) ...{
this.input = input;
}
![]()
![]()
public Collection getCountryItems() ...{ //给下拉框赋值
SelectItem aa= new SelectItem();
if (countryItems == null) ...{
countryItems = new ArrayList();
countryItems.add(new SelectItem("Sun", "Sun", null));
countryItems.add(new SelectItem("Month", "Month", null));
countryItems.add(new SelectItem("Earth", "Earth", null));
}
return countryItems;
}
![]()
public void setCountryItems(ArrayList<SelectItem> countryItems) ...{
this.countryItems = countryItems;
}
![]()
}
0
相关文章