JSF基于另一个更新selectOneMenu

时间:2013-10-04 20:02:05

标签: jsf jsf-2 primefaces selectonemenu

我是JSF的新手,遇到了问题。

我有一个selectOneMenu用于显示国家/地区列表。当用户选择其中一个国家/地区时,应该自动填充另一个具有城市(=我的区域)的selectOneMenu。

我尝试了几次迭代,但没有帮助。 如果还需要其他任何东西来帮助我,请告诉我。真的很感激。

更新:

这是添加监听器后的代码:

     <p:outputLabel for="countryRegistration">#{msg['country']}:</p:outputLabel>
    <p:selectOneMenu id="countryRegistration" value="#{mbcActor.geoData.country}" style="width:120px;" >
        <f:attribute name="country" value="java.util.List" />
        <f:converter converterId="ViewScopedObjectConverter"/>
        <f:selectItem itemLabel="#{msg['selectCountry']}" itemValue=""/>
        <f:selectItems value="#{geoLists.countryList}" var="country" itemLabel="#{country.name}"/>
        <p:ajax listener="#{mbcActor.geoData.updateRegions}" render="cityRegistration"/>
    </p:selectOneMenu>

    <p:message for="countryRegistration"/>

    <p:outputLabel for="cityRegistration">#{msg['city']}:</p:outputLabel>

    <p:selectOneMenu id="cityRegistration" value="#{mbcActor.geoData.region}" style="width:120px;">
        <f:attribute name="regions" value="java.util.List" />
        <f:converter converterId="ViewScopedObjectConverter"/>
        <f:selectItem itemLabel="#{msg['selectCity']}" itemValue=""/>
        <!--<f:selectItems value="#{geoLists.regionForCountry}" var="region" itemLabel="#{region.name}"/>-->
        <f:selectItems value="#{geoLists.getRegionForCountry(country)}"  var="region" itemLabel="#{region.description}"/>
    </p:selectOneMenu>
    <p:message for="cityRegistration"/>

但它说:

        Oct 05, 2013 2:04:53 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: Target Unreachable, identifier 'mbcActor' resolved to null
javax.el.PropertyNotFoundException: Target Unreachable, identifier 'mbcActor' resolved to null
    at org.apache.el.parser.AstValue.getTarget(AstValue.java:98)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:259)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processCustomListener(AjaxBehaviorListenerImpl.java:70)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:59)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:47)

豆类:

package xxx.core.entities;

// Generated Oct 20, 2009 11:07:18 AM by Hibernate Tools 3.2.2.GA

import javax.faces.event.ValueChangeEvent;
import javax.inject.Inject;
import javax.persistence.*;

import java.util.ArrayList;
import java.util.List;

import static javax.persistence.GenerationType.IDENTITY;

/**
 * DataActorGeo
 */
@Entity
@Table(name = "dataActorGeo")
// @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Access(AccessType.PROPERTY)
public class DataActorGeo implements java.io.Serializable {

    private Integer id;
    private Country country;
    private Region region;
    private String city;
    private String province;
    private String address;
    private String addressLine2;
    private String postCode;
    private String nationality;
    private String phone1;
    private String phone2;

    private Double latitude;
    private Double longitude;

    private Actor actor;
    private List<Region> regions;

    @Inject
    EntityManager entityManager;

    public void updateRegions() {
        //Country ctry = (Country) event.getNewValue();
        try{
            System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
        //    if (regions == null) {
                this.regions = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
                        .setParameter("countryId", country.getId())
                        .getResultList();
                //countryIdCache = country.getId();
          //  }
            System.out.println("aaaaaaaaaaa" + regions.toString());
        } catch(Exception e){System.out.println("cccccccccc"); }//return new ArrayList<Region>(); }
        //return regions;
    }

    public DataActorGeo() {
    }

    public DataActorGeo(Country country, String city) {
        this.country = country;
        this.city = city;
    }

    public DataActorGeo(Country country, Region region, String city, String address, String postCode, String phone1, String phone2, Actor actor) {
        this.country = country;
        this.region = region;
        this.city = city;
        this.address = address;
        this.postCode = postCode;
        this.phone1 = phone1;
        this.phone2 = phone2;
        this.actor = actor;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "Country")
    // @IndexedEmbedded(prefix = "country.")
    public Country getCountry() {
        return this.country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "Region")
    // @IndexedEmbedded(prefix = "region.")
    public Region getRegion() {
        return this.region;
    }

    public void setRegion(Region region) {
        this.region = region;
    }

    public List<Region> getRegions()
    {
        return this.regions;
    }

    public void setRegions(List<Region> regions)
    {
        this.regions=regions;
    }

    @Column(name = "City")
    // //@Field(index = Index.UN_TOKENIZED)
    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Column(name = "province")
    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    @Column(name = "address")
    // //@Field(index = Index.TOKENIZED)
    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Column(name = "addressLine2")
    // //@Field(index = Index.TOKENIZED)
    public String getAddressLine2() {
        return addressLine2;
    }

    public void setAddressLine2(String addressLine2) {
        this.addressLine2 = addressLine2;
    }

    @Column(name = "postCode")
    // //@Field(index = Index.UN_TOKENIZED)
    public String getPostCode() {
        return this.postCode;
    }

    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }

    @Column(name = "nationality")
    // //@Field(index = Index.UN_TOKENIZED)
    public String getNationality() {
        return nationality;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    @Column(name = "phone1")
    // //@Field(index = Index.UN_TOKENIZED)
    public String getPhone1() {
        return phone1;
    }

    public void setPhone1(String phone1) {
        this.phone1 = phone1;
    }

    @Column(name = "phone2")
    // //@Field(index = Index.UN_TOKENIZED)
    public String getPhone2() {
        return phone2;
    }

    public void setPhone2(String phone2) {
        this.phone2 = phone2;
    }

    @OneToOne(mappedBy = "geoData")
    public Actor getActor() {
        return actor;
    }

    public void setActor(Actor actor) {
        this.actor = actor;
    }

    @Column(name = "latitude")
    public Double getLatitude() {
        return latitude;
    }

    @Column(name = "longitude")
    public Double getLongitude() {
        return longitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }
}









package xxx.lists;

import xxx.application.configuration.ISNetApp;
import xxx.core.entities.Country;
import xxx.core.entities.Region;

import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Named
@ViewScoped
public class GeoLists implements Serializable {

    @Inject
    EntityManager entityManager;

    @Inject
    ISNetApp sNetApp;

    private List<Country> countryList;

    public List<Country> getCountryList() {
        if (countryList == null) {
            String query = "select c from Country c order by c.ordering, c.name";
            countryList = (List<Country>) entityManager.createQuery(query).getResultList();
        }
        return countryList;
    }

    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }

    private List<Country> deliveryCountryList;

    public List<Country> getDeliveryCountryList() {
        if (deliveryCountryList == null) {
            String query = "select c from Country c where c.groups LIKE '%D,%' order by c.ordering, c.name";
            deliveryCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
        }
        return deliveryCountryList;
    }

    public void setDeliveryCountryList(List<Country> deliveryCountryList) {
        this.deliveryCountryList = deliveryCountryList;
    }

    public Country getCountryByIsoCode2(String isoCode2) {
        String query = "select c from Country c where c.isoCode2=:ic";
        try {
            return (Country) entityManager.createQuery(query).setParameter("ic", isoCode2).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    private List<Region> regionForCountry;
    private int countryIdCache;

    private List<Region> regions;

    public List<Region> getRegions(){
        return this.regions;
    }

    public void setRegions(List<Region> regions){
        this.regions = regions;

    }

    public List<Region> getRegionForCountryById(Long countryId) {
        Country country = entityManager.find(Country.class, countryId.intValue());
        return getRegionForCountry(country);
    }

    public List<Region> getRegionForCountry(Country country) {
        try{
            System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
            //if (regionForCountry == null || countryIdCache != country.getId()) {
            regionForCountry = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
                    .setParameter("countryId", 1)//country.getId())
                    .getResultList();
            //  countryIdCache = country.getId();
            //}
            //  System.out.println("aaaaaaaaaaa" + regionForCountry.toString());
        } catch(Exception e){System.out.println("cccccccccc"); return new ArrayList<Region>(); }
        return regionForCountry;
    }

    public void setRegionForCountry(List<Region> regionForCountry) {
        this.regionForCountry = regionForCountry;
    }

    private Country mainCountry;

    private Country country;
    public void setCountry(Country country) {
        this.country=country;
    }

    public Country getCountry(){
        return this.country;
    }

    public Country getMainCountry() {
        if (mainCountry == null) {
            mainCountry = entityManager.find(Country.class, sNetApp.getMainCountryId());
        }
        return mainCountry;
    }

    public void setMainCountry(Country mainCountry) {
        this.mainCountry = mainCountry;
    }

    private List<Country> specificGroupCountryList;
    private String groupCache;

    public List<Country> getSpecificGroupCountryList(String group) {
        if (specificGroupCountryList == null || groupCache == null || groupCache.compareTo(group) != 0) {
            String query = "from Country where groups LIKE '%" + group + ",%' order by ordering, name";
            specificGroupCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
        }
        return specificGroupCountryList;
    }

    public void setSpecificGroupCountryList(List<Country> specificGroupCountryList) {
        this.specificGroupCountryList = specificGroupCountryList;
    }

}

mbcActor是一个定义为:

的参数
<ui:param name="mbcActor" value="#{registrationHelper.newActor}"/>

AbstractActor:

@MappedSuperclass
public class AbstractActor extends AbstractGenericElement implements java.io.Serializable, IGenericElement, EmailContact {

    private static Logger log = LoggerFactory.getLogger(AbstractActor.class);

    public static enum Gender {
        Male,
        Female
    }

    /**
     * Transient
     */
    private boolean selected;

    private Integer id;
    private Long version;
    private byte type;
    private String language;
    private byte status;
    private byte publicStatus;
    private String permalink;
    private Boolean customPermalink;
    private String displayName;
    private String forename;
    private String surname;

    private Gender gender;
    private Date birthday;

    private String mobile;

    private Byte subType;

    private String stringValue1;
    private String stringValue2;
    private String stringValue3;

    @Transient
    @XmlTransient
    private Integer age;

    private String profileMessage;
    private String statusMessage;
    private String email;
    private String username;

    private String passwordHash;
    private int passwordHashIterations;
    private String salt;

    private String timezone;

    private String activationCode;
    private Boolean activationEmailSent;

    private Integer completitionPercentage;

    private Integer ordering;

    // Stats
    private ActorStats stats;

    // Extensions
    private DataActorGeo geoData;
    private DataActorExtended dataActorExtended;

    private Boolean acceptNewsletter;
    private Boolean emailAlertsEnabled;

    private Set<ActorTag> actorTags = new HashSet<ActorTag>(0);

    private List<Role> roles = new ArrayList<Role>(0);

    private Actor newDataToBeModerated;

    private Date expireDate;

    private Integer points;
    private BigDecimal wallet;

    private Byte emailAlertsType;
    private Byte emailOffersType;

    private String emailHash;

    // Data blob
    private byte[] data;

    private Set<ActorInCategory> actorInCategories = new HashSet<ActorInCategory>(
            0);

    private List<ActorAttribute> actorAttributes = new ArrayList<ActorAttribute>(0);


    public AbstractActor() {
        this.version = 1l;
        this.activationEmailSent = false;
        this.acceptNewsletter = true;
        this.emailAlertsEnabled = true;
        this.completitionPercentage = 0;
        this.customPermalink = false;
        this.wallet = new BigDecimal(0);
        this.points = 0;
        this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
        this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
    }

    public AbstractActor(byte type, byte status) {
        this.version = 1l;
        this.type = type;
        this.status = status;
        this.publicStatus = ActorConstants.PUBLIC_STATUS_OFFLINE;
        this.activationEmailSent = false;
        this.acceptNewsletter = true;
        this.emailAlertsEnabled = true;
        this.completitionPercentage = 0;
        this.customPermalink = false;
        this.wallet = new BigDecimal(0);
        this.points = 0;
        this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
        this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
    }

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "geoData", nullable = true)
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public DataActorGeo getGeoData() {
        return this.geoData;
    }

    public void setGeoData(DataActorGeo geoData) {
        this.geoData = geoData;
    }


    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
    public Set<ActorInCategory> getActorInCategories() {
        return this.actorInCategories;
    }

    public void setActorInCategories(Set<ActorInCategory> actorInCategories) {
        this.actorInCategories = actorInCategories;
    }

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
    public List<ActorAttribute> getActorAttributes() {
        return this.actorAttributes;
    }

    public void setActorAttributes(List<ActorAttribute> actorAttributes) {
        this.actorAttributes = actorAttributes;
    }
}

2 个答案:

答案 0 :(得分:1)

您的<p:ajax>代码使用render属性,该属性未预定义。您想要的属性是update

答案 1 :(得分:0)

假设registrationHelper.newActor是Managed Bean的一个实例,我认为它可能没有初始化。你为什么不通过在RegistrationHelper的PostConstruct上创建它来确定它,或者甚至通过像

这样的方法来实现它
public AbstractActor createNewActor() {
        newActor = new AbstractActor();
    return newActor;
    }

<ui:param name="mbcActor" value="#{registrationHelper.createNewActor}"/>