无法在JSF托管bean

时间:2015-09-02 03:50:49

标签: java jsf tomcat cdi

在我的JSF托管bean(HomePageController.java)中我试图使用@Resource注释获取数据库连接,但由于某种原因它仍然是null,而在调试时我发现它给出{ {1}}。

我正在使用Tomcat 8服务器。这可能是因为Tomcat 8不是一个功能齐全的Java EE容器吗?

我已经在META-INF / context.xml文件中定义了数据源

NullPointerException

web.xml代码段

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/ministore-jsf-mvc">
    <!-- PostgreSQL Datasource -->
    <Resource auth="Container" driverClassName="org.postgresql.Driver"
              factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
              maxActive="50" maxIdle="10" maxWait="-1"
              name="jdbc/ministore-db" password="postgres"
              type="javax.sql.DataSource"
              url="jdbc:postgresql://db-server:5432/ministore-db" username="postgres"/>
</Context>

HomePageController.java

<!-- DB configuration (using Datasource) -->
<resource-ref>
    <description>PostgreSQL Datasource</description>
    <res-ref-name>jdbc/ministore-db</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

输出:

@ManagedBean
@RequestScoped
public class HomePageController implements Serializable {

    private static final Logger LOG = Logger.getLogger(HomePageController.class);

    @Resource(name = "jdbc/ministore-db")
    protected DataSource dataSource;

    public Product getProduct() {
        LOG.debug("Into the HomePageController...");

        //get the Product object based on productId parameter
        Product product = null;

        try {
            product = new MasterDao(dataSource).getProduct(DEFAULT_PRODUCT_ID);
            LOG.debug("product = " + product);
        } catch (Exception e) {
            LOG.error("Exception while getting product from DB for productId = " + DEFAULT_PRODUCT_ID);
            LOG.error(e.getMessage());
        }
        LOG.debug("product = " + product);
        return product;
    }

}

1 个答案:

答案 0 :(得分:0)

试试这个

 @Resource(name = "java:/comp/env/jdbc/ministore-db")

同时从您的上下文文件中删除factory属性