lundi 24 juin 2019

Why JNDI InitialContext can work fine in jsp but not in a class?

I'm working with Database connection using JNDI. I'm sure the deployment is fine. Because when I test it in the JSP below, it works fine.

</head> 
<body> 
<% 
try { 
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource)envCtx.lookup("jdbc/airlineticket");
    Connection conn = ds.getConnection();
out.println(conn); 
conn.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
}
%> 
</body> 
</html>

success connection picture

But when I use ConnectionFactory class, an error occurs: ConnectionFactory cannot be resolved. I just put the connection code in the ConnectionFactory class, why this happened? ConnectionFactory class:

public static Connection getConnection()
{
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource)envCtx.lookup("jdbc/airlineticket");
        return ds.getConnection();
    }
    catch (NamingException e)
    {
        System.out.print("connection failed");
        return null;
    }
    catch(SQLException e)
    {
        e.printStackTrace();
        return null;
    }
}

test JSP:

</head> 
<body>     
<% 
try {       
Connection conn = ConnectionFactory.getConnection(); 
out.println(conn); 
conn.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
}
%> 
</body> 
</html>

web.xml(/WEB-INF/web.xml):

<resource-ref>
  <res-ref-name>jdbc/airlineticket</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

context.xml(/META-INF/context.xml):

<Context>
    <Resource name="jdbc/airlineticket" 
        auth="Container" 
        type="javax.sql.DataSource"
        username="Manager" 
        password="123456"
        driverClassName="org.mariadb.jdbc.Driver"
        url="jdbc:mariadb://localhost:3306/airlineticket"
        maxActive="50"
        masIdle="20"> </Resource>
</Context>




Aucun commentaire:

Enregistrer un commentaire