我有两个h:selectOneMenu(1:国家,2:城市)。我需要使用ajax从城市selectOneMenu中的一个选定国家/地区加载所有城市。当我更改国家/地区的值时,selectOneMenu我的城市selectOneMenu从countryBean.selectedCountry获取空值。
<h:panelGrid columns="2">
<h:outputLabel for="countries" value="Countries: " />
<h:selectOneMenu converter="omnifaces.SelectItemsConverter"
id="countries" required="true" value="#{countryBean.selectedCountry}">
<f:selectItem itemLabel="Choose country" />
<f:selectItems value="#{countriesBB.findAllCountries()}"
var="country" itemLabel="#{country.name}" />
<f:ajax event="change" render="cities" />
</h:selectOneMenu>
<h:outputLabel for="cities"
value="Cities: " />
<h:selectOneMenu converter="omnifaces.SelectItemsConverter"
id="cities" required="true"
value="#{cityBean.selectedCity}">
<f:selectItem itemLabel="Choose city" />
<f:selectItems value="#{cityBean.findAllCitiesByCountry(countryBean.selectedCountry)}"
var="city" itemLabel="#{city.name}" />
</h:selectOneMenu>
</h:panelGrid>
这是找到城市的方法:
public List<city> findAllCitiesByCountry(Country country) {
List<City> cities = null;
try {
cities = citiesService.findAllCitiesByCountry(country);
} catch (Exception exception) {
logger.debug("Error finding cities.", exception);
}
return cities;
}
我收到NullPointerException,因为countryBean.selectedCountry始终为null。这样做的正确方法是什么?
答案 0 :(得分:2)
JSF初学者需要了解的众多规则之一:
一旦你试图通过保持你的getter方法真正的getter方法(即除了return property;
之外不做任何事情)并在(post)构造函数和/或action(listener)方法中执行业务逻辑来解决这个问题那么这个特殊的问题就会消失。
这是一个启动示例:
<h:selectOneMenu value="#{bean.country}">
<f:selectItems value="#{bean.countries}" ... />
<f:ajax listener="#{bean.changeCountry}" render="cities" />
</h:selectOneMenu>
<h:selectOneMenu id="cities" value="#{bean.city}">
<f:selectItems value="#{bean.cities}" ... />
</h:selectOneMenu>
在@ViewScoped
bean中使用类似的东西:
private Country country; // +getter+setter
private City city; // +getter+setter
private List<Countries> countries; // +getter
private List<Cities> cities; // +getter
@EJB
private SomeService service;
@PostConstruct
public void init() {
countries = service.getCountries();
}
public void changeCountry() {
cities = service.getCities(country);
}