2013-08-28 3 views
1

두 개의 h : selectOneMenu (1 : Countries, 2 : Cities)가 있습니다. ajax를 사용하여 도시 selectOneMenu에서 선택한 국가의 모든 도시를로드해야합니다. 국가 selectOneMenu의 값을 변경할 때 내 도시 selectOneMenu는 countryBean.selectedCountry에서 Null 값을 가져옵니다. countryBean.selectedCountry는 항상 null이기 때문에Loading h : 다른 h에 따라 selectOneMenu : selectOneMenu 값

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이 점점 오전 :

<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> 

은 도시를 찾는 방법입니다. 이 작업을 수행하는 올바른 방법은 무엇입니까? JSF 스타터가 알아야 할 많은 규칙

답변

2

하나 :

  • 는 getter 메소드에 비즈니스 로직을 수행하지 마십시오.

당신이 당신의 getter 메소드를 유지하여 진정한 getter 메소드가와 (포스트) 생성자 및/또는 행동 (청취자) 메소드에 비즈니스 로직을 수행하는 (즉, 그냥 return property; 이상의 다른 작업을 수행하지 않음) 것을 해결하려고하면 , 이 특별한 문제는 사라질 것입니다. @ViewScoped 콩에서이 같은으로

<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> 

: : 나는 콩의 범위를 되풀이 가치가 BalusC 언급처럼 중요하다고 생각

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); 
} 
+0

는 여기에 킥오프 예입니다. 예를 들어 @RequestScoped를 사용하면 양식을 제출할 때마다 클래스의 새 인스턴스가 호출됩니다. 유효성 검사에 실패하고 동일한 페이지로 돌아 가면 문제가 발생하기 시작합니다. – Amin

관련 문제