【问题标题】:Fields of injected bean are null when trying to set them via JSF [duplicate]尝试通过 JSF 设置注入 bean 的字段时为空 [重复]
【发布时间】:2017-06-23 12:18:08
【问题描述】:

我正在关注一本关于 JEE 的书,并尝试实现一个简单的 JSF 示例。我想通过 JSF 页面和控制器注册并保留一个 Customer

问题是控制器中注入的 Customer 的属性始终为空,无论我在 JSF 注册表单中键入什么。

不过,registerController.persist() 方法会在表单提交时执行。

例如,当我使用电子邮件“user@email.com”提交表单时,我希望控制器中注入的客户有一封电子邮件,但它始终为空。也许有人可以给我一个问题所在的建议。

JSF 页面:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <title>
        <h:outputText value="Onlineshop"/>
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</h:head>
<h:body>
    <h:form>
        <h:panelGrid columns="2">
            <f:facet name="header">
                <h:outputText value="Registrieren"/>
            </f:facet>
            <h:outputLabel value="E-Mail:"/>
            <h:inputText value="#{registerController.customer.email}"></h:inputText>
            <h:outputLabel value="Kennwort:"/>
            <h:inputSecret value="#{registerController.customer.password}"></h:inputSecret>
            <h:commandButton action="#{registerController.persist}" value="Registrieren"/>
        </h:panelGrid>
    </h:form>
</h:body>
</html>

控制器:

package de.java2enterprise.onlineshop;

import de.java2enterprise.onlineshop.model.Customer;

import javax.annotation.Resource;
import javax.faces.bean.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;

@Named
@RequestScoped
public class RegisterController {

    @PersistenceUnit()
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction ut;

    @Inject
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public String persist() {
        try {
            ut.begin();
            emf.createEntityManager().persist(customer);
            ut.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/register.xhtml";
    }
}

还有客户:

package de.java2enterprise.onlineshop.model;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * 
 * @author Alexander Salvanos
 *
 * The persistent class for the CUSTOMER database table.
 * 
 */
@Entity
@Table(schema="ONLINESHOP", name="CUSTOMER")
@NamedQuery(
        name="Customer.findAll", 
        query="SELECT c FROM Customer c")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(
            name="CUSTOMER_ID_GENERATOR", 
            sequenceName="SEQ_CUSTOMER",
            schema="ONLINESHOP",
            allocationSize=1,
            initialValue=1)
    @GeneratedValue(
            strategy=GenerationType.SEQUENCE, 
            generator="CUSTOMER_ID_GENERATOR")
    private Long id;

    private String email;

    private String password;

    //bi-directional many-to-one association to Item
    @OneToMany(mappedBy="seller")
    private Set<Item> offers;

    //bi-directional many-to-one association to Item
    @OneToMany(mappedBy="buyer")
    private Set<Item> purchases;

    public Customer() {
    }

    public Long getId() {
        return this.id;
    }

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

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Set<Item> getOffers() {
        return this.offers;
    }

    public void setOffers(Set<Item> offers) {
        this.offers = offers;
    }

    public Item addOffer(Item offer) {
        Set<Item> offers = getOffers();
        if(offers == null) {
            offers = new HashSet<Item>();
        }
        offers.add(offer);
        offer.setSeller(this);

        return offer;
    }

    public Item removeOffer(Item offer) {
        getOffers().remove(offer);
        offer.setSeller(null);

        return offer;
    }

    public Set<Item> getPurchases() {
        return this.purchases;
    }

    public void setPurchases(Set<Item> purchases) {
        this.purchases = purchases;
    }

    public Item addPurchase(Item purchase) {
        Set<Item> purchases = getPurchases();
        if(purchases == null) {
            purchases = new HashSet<Item>();
        }
        purchases.add(purchase);
        purchase.setBuyer(this);
        return purchase;
    }   

    public Item removePurchase(Item purchase) {
        getPurchases().remove(purchase);
        purchase.setBuyer(null);

        return purchase;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) obj;
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        return true;
    }

    public String toString() {
        return id + "-" + email + "-" + password;
    }
}

【问题讨论】:

  • 你注入的实体有值吗?还是null
  • 它有值,但它的所有字段都是空的。
  • 使用javax.enterprise.context.RequestScoped 包而不是javax.faces.bean.RequestScoped。可能不是问题,但您不能混合使用 JSF 和 CDI 注释。
  • 谢谢@Rouliboy 就是这样,现在终于可以工作了。也许您可以在此处发布答案,以便我将其标记为最佳答案。
  • 太棒了!我发布了一个答案。

标签: jsf cdi


【解决方案1】:

您正在混合使用JSFCDI 注释,使用javax.inject.Named (CDI) 和javax.faces.bean.RequestScoped (JSF)。

请改用 javax.enterprise.context.RequestScoped

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 2013-04-16
    • 2012-04-09
    • 2012-10-01
    • 2011-11-26
    • 2023-03-30
    • 2019-07-05
    • 2016-05-09
    • 2011-03-15
    相关资源
    最近更新 更多