作者: Chris http://jroller.com/page/cschalk?entry=building_dependent_select_menus_in
翻译: icess http://blog.matrix.org.cn/page/icess
在web程序中,有时候需要管理的选择按钮,(译者注:如注册qq号码时候选择省份和地区,地区是根据省份的不同来动态变化的) 在jsf中实现这种选择按钮可以有多种方式(译者注:现在使用ajax4jsf可以实现更友好的组件),这里提供一个比较简单的实现.
Defining the HashMaps as managed beansFaces提供了在配置文件中直接声明Lists和Maps 为managed bean的功能 .一旦在 faces-config.xml中定义, Faces apps就可以通过EL表达式来使用她了, 我们定义下面的Maps
CountriesMap - A Map of countries: France, United States, India.
该Map将驱动一些Maps: UsCitiesMap, FrCitiesMap and InCitiesMap.
当用户选择一个国家名,依赖的list将会根据国家名自动加载.
The HashMapsCountriesMap
<managed-bean> |
And the dependent city Maps..
UsCitiesMaps
<managed-bean> |
FrCitiesMaps
<managed-bean> |
InCitiesMap
<managed-bean> |
在选择国家以前为了显示一些提示,我们提供一个 EmptyCities Map
EmptyCitiesMap
<managed-bean> |
注意,这些Maps也可以从其他地方动态的建立和驱动,如数据库
下面的包含两个select menus的jsp代码.
<%@ page contentType="text/html;charset=windows-1252"%> |
页面包含两个selectOneMenu 组件,和他们的子组件 selectItems 被绑定到faces配置文件中配置的#{CountriesMap} 中, 和一个依靠选择的国家名来改变的城市list #{Deplist_backing.cities} Deplist_backing 对象是一个 managed bean 代码如下:
package backing;
import java.util.Map;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
public class DepList {
HtmlSelectOneMenu inputCountry, inputCity;
// Method which returns the cities Map
// based on the value of inputCountry
public Map getCities() {
String cityMap = "";
if (inputCountry.getValue() != null) {
String countryKey = inputCountry.getValue().toString();
if (countryKey.equals("fr"))
cityMap = "FrCitiesMap";
else if (countryKey.equals("us"))
cityMap = "UsCitiesMap";
else if (countryKey.equals("in"))
cityMap = "InCitiesMap";
else
cityMap = "EmptyCitiesMap";
}
else {
cityMap = "EmptyCitiesMap";
}
cityMap = "#{" + cityMap + "}";
//retrieve correct cityMap and return
FacesContext context = FacesContext.getCurrentInstance( );
ValueBinding binding;
binding = context.getApplication().createValueBinding(cityMap);
return (Map) binding.getValue(context);
}
public void setInputCountry(HtmlSelectOneMenu inputCountry) {
this.inputCountry = inputCountry;
}
public HtmlSelectOneMenu getInputCountry() {
return inputCountry;
}
public void setInputCity(HtmlSelectOneMenu inputCity) {
this.inputCity = inputCity;
}
public HtmlSelectOneMenu getInputCity() {
return inputCity;
}
} |
注意getCities方法是如何检测是否inputCountry中有输入值,如果有意味着要根据选择的国家来加载城市Map. 这是通过访问managed bean中的city Map来完成的..
And finally the registration of the class Deplist as managed bean Deplist_backing.
<managed-bean> <managed-bean-name>Deplist_backing</managed-bean-name> <managed-bean-class>backing.DepList</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> |
And that's it.. when you run the JSP page, you will be able to select the country first and then select the city name.
本文介绍如何在JSF中实现依赖级联选择框,通过配置不同国家对应的多个城市映射,根据用户选择的国家动态加载对应的城市列表。
682

被折叠的 条评论
为什么被折叠?



