Obtain a remote connection to a DataSource or EJB (Weblogic)Tag(s): Servlet/JSP


It's possible to obtain a remote connection to a Datasource defined in the application server. In this example, the connection is made to a Weblogic server so you need wlclient.jar in the classpath.
import java.sql.*;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

public class RemoteConnection {
    private RemoteConnection() { }

    public static void main(String args[]) throws Exception {
        Properties env = new Properties();
        String datasourceName = "mydatasourcename";
        env.put("java.naming.factory.initial",
                "weblogic.jndi.WLInitialContextFactory");
        env.put("java.naming.provider.url",
                "t3://xxxxxxxx-xxxxx.xxx.xxxxx:7101");
        InitialContext ctxProxy = new InitialContext(env);
        Object dsObj = ctxProxy.lookup(datasourceName);
        DataSource ds = (DataSource) PortableRemoteObject.narrow(dsObj,
                javax.sql.DataSource.class);
        PreparedStatement ps = null;
        Connection conn = null;
        ResultSet result = null;
        try {
            conn = ds.getConnection();
            String SelectString = "SELECT NAME, ADDRESS FROM EMPLOYEE";
            ps = conn.prepareStatement(SelectString);
            for (result = ps.executeQuery(); result.next();) {
                String data = result.getString(1) + " : " + result.getString(2);
                System.out.println(data);
            }
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        } 
        finally {
            result.close();
            ps.close();
            conn.close();
            conn = null;
            ps = null;
            result = null;
        }
    }
}
The next example, make a remote call to an EJB host in a Weblogic server. You need wlclient and the EJB client jars in the classpath.
import java.util.Properties;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import com.company.common.myejb.*;

public class RemoteEJBCall {
    private RemoteEJBCall() {  }

    public static void main(String args[]) throws Exception {
        Properties env = new Properties();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                "weblogic.jndi.WLInitialContextFactory");
        env.put(javax.naming.Context.PROVIDER_URL,
                "t3://xxxxxxxx-xxxxx.xxx.xxxxx:7101");
        InitialContext ctx = new InitialContext(env);
        Object obj = ctx.lookup("common/MyEJB");

        MyEJBHome home = (((MyEJBHome) PortableRemoteObject
                .narrow(obj, MyEJBHome.class)));
        MyEJB myEJB = home.create();

        System.out.println(myEJB.doit());
    }
}

blog comments powered by Disqus