JBoss EAP 7 与 Oracle 数据源

JBoss EAP 7 with Oracle Datasource

我正在尝试使用 Jboss 数据源访问 Oracle 数据库连接,但它正在抛出 java.lang.NullPointerException。

下面是我的代码,jboss 在启动期间显示在下面的日志中。 我的代码有什么问题?

 WFLYJCA0001: Bound data source [java:/jdbc/testOracleDS]




@WebServlet("/Index")
public class Index extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private DataSource dataSource;
    Connection conn = null;

    public Index() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init() throws ServletException {

        try {
            DataSource anotherDataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            conn = dataSource.getConnection();
            System.out.println("connection established");
            response.getWriter().println("connection established");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("failed to establish connection: " + e);
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

我通过调整代码解决了这个问题,数据源变量没有正确初始化

public class 索引扩展 HttpServlet { private static final long serialVersionUID = 1L;

private DataSource dataSource;
Connection conn = null;

public Index() {
    super();
    // TODO Auto-generated constructor stub
}

public void init() throws ServletException {

    try {
       dataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        conn = dataSource.getConnection();
        System.out.println("connection established");
        response.getWriter().println("connection established");
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().println("failed to establish connection: " + e);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}}