jndi Posts

Connecting MyBatis ORM to C3P0 Connection Pooling

In this example, im trying to connecting my MyBatis application to my database through C3P0 connection pooling. According to its website, C3P0 is an easy-to-use library for making traditional JDBC drivers “enterprise-ready” by augmenting them with functionality defined by the jdbc3 spec and the optional extensions to jdbc2.

Okay, so the first thing i do is, creating a database named “Test” and table “Testing”

CREATE DATABASE `Test`;
USE `Test`;
CREATE TABLE `testing` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL DEFAULT '',
  `address` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`Id`),
  UNIQUE KEY `ix` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

insert into `table`(`Id`,`name`,`address`) values (1,'edw','Ciledug');
insert into `table`(`Id`,`name`,`address`) values (2,'kamplenk','Cikokol');
insert into `table`(`Id`,`name`,`address`) values (3,'nugie','Pamulang');
insert into `table`(`Id`,`name`,`address`) values (4,'tebek','Karawaci');

And a java bean class to represent my sql table,

package com.edw.bean;

public class Testing {

    private int id;
    private String name;
    private String address;

    public Testing() {
    }

    // setter and getter method

    @Override
    public String toString() {
        return "Testing{" + "id=" + id + ", name=" + name + ", address=" + address + '}';
    }
}

and dont forget, a java interface class to handle my query

package com.edw.mapper;

import com.edw.bean.Testing;
import java.util.List;
import org.apache.ibatis.annotations.Select;
 
public interface TestingMapper {
    @Select("SELECT * FROM testing")
    List<Testing> selectAll();
}

Next is creating c3p0 connection configuration on context.xml file under META-INF folder

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/MyBatisC3P0">
	
    <Resource name="testjndi" 
		 auth="Container"
		 driverClass="com.mysql.jdbc.Driver"
         jdbcUrl="jdbc:mysql://localhost:3306/test"
         user="root"
         password="xxxx"					 		 
         factory="org.apache.naming.factory.BeanFactory" 
         type="com.mchange.v2.c3p0.ComboPooledDataSource" 
         maxPoolSize="30" 					 
         minPoolSize="10" 
         acquireIncrement="3" 
         acquireRetryAttempts = "0"
         acquireRetryDelay = "3000"
         breakAfterAcquireFailure = "false"
         maxConnectionAge = "20"
         maxIdleTime = "15"
         maxIdleTimeExcessConnections = "15"
         idleConnectionTestPeriod = "10"
         testConnectionOnCheckout = "true"					 
         preferredTestQuery = "SELECT 1"
         debugUnreturnedConnectionStackTraces = "true"					 
         autoCommitOnClose="true"
        />	
</Context>

next is registering your JNDI on web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>myBatisServlet</servlet-name>
        <servlet-class>com.edw.servlet.MyBatisServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myBatisServlet</servlet-name>
        <url-pattern>/myBatisServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>myBatisServlet</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>My Connection Pool</description>
        <res-ref-name>testjndi</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

and calling your connection pooling jndi from MyBatis’ xml code

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
       <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="data_source" value="java:/comp/env/testjndi"/>
            </dataSource>
        </environment>          
    </environments>
    <mappers />
</configuration>

next is creating a java class to load my MyBatis’ xml configuration

package com.edw.config;

import com.edw.mapper.TestingMapper;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisSqlSessionFactory {

    private static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
            FACTORY.getConfiguration().addMapper(TestingMapper.class);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

and finally, i create a servlet as my presentation layer

package com.edw.servlet;

import com.edw.bean.Testing;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.TestingMapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

public class MyBatisServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession(true);
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MyBatisServlet</title>");
            out.println("</head>");
            out.println("<body>");

            TestingMapper testingMapper = sqlSession.getMapper(TestingMapper.class);
            List<Testing> testings = testingMapper.selectAll();
            for (Testing testing : testings) {
                out.println(testing.getName()+" - "+testing.getAddress()+"<br />");
            }
            
            out.println("</body>");
            out.println("</html>");
        } finally {
            sqlSession.close();
            out.flush();            
            out.close();            
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is what the result of my servlet when im running it on my browser

This is the screenshot of my database connection, you can see that c3p0 automatically create 10 free connections.

And this is the screenshot of my netbeans project

Have fun with C3P0 and MyBatis (H)

Google+

Setting Up C3P0 Connection Pooling on Apache Tomcat

My using this configuration on my Apache Tomcat 7 for my heavy-load application, and it runs very well. I put this code on context.xml under Apache Tomcat’s conf folder.

<Resource name="myconnection" auth="Container"
	driverClass="com.mysql.jdbc.Driver"
	jdbcUrl="jdbc:mysql://localhost:3306/mydatabase"
	user="root"
	password="xxxx"                                                      
	factory="org.apache.naming.factory.BeanFactory" 
	type="com.mchange.v2.c3p0.ComboPooledDataSource" 
	maxPoolSize="50" 	
	minPoolSize="15" 
	acquireIncrement="3" 
	acquireRetryAttempts = "0"
	acquireRetryDelay = "3000"
	breakAfterAcquireFailure = "false"
	maxConnectionAge = "60"
	maxIdleTime = "30"
	maxIdleTimeExcessConnections = "10"
	idleConnectionTestPeriod = "15"
	testConnectionOnCheckout = "true"
	preferredTestQuery = "SELECT 1"
	debugUnreturnedConnectionStackTraces = "true"	
	autoCommitOnClose="true"
	/>

I use MySql’s command “SHOW PROCESSLIST” for checking on opened connection to MySql.

I hope it helped others.
:-[

Google+

Beginning MyBatis : DataSource, JNDI and Apache DBCP

In this tutorial, im trying to connect a servlet to mysql database using Apache DBCP. Im using mybatis and accessing Apache DBCP’s datasource via JNDI. Btw, im using Netbeans 6.9 and Apache Tomcat 6.

First as always, a table named “contoh” on a database “test”

CREATE
    TABLE contoh
    (
        nama VARCHAR(30) NOT NULL,
        alamat VARCHAR(100),
        PRIMARY KEY (nama)
    )

insert into contoh (nama, alamat) values ('edwin', 'singapore');
insert into contoh (nama, alamat) values ('kamplenk', 'ciledug');
insert into contoh (nama, alamat) values ('nugie', 'pamulang');
insert into contoh (nama, alamat) values ('samsu', 'dago');
insert into contoh (nama, alamat) values ('tebek', 'karawaci');	

and a simple java bean

package com.edw.mybatis.bean;

import java.io.Serializable;

public class Contoh implements Serializable {
    private String nama;
    private String alamat;

	// other setter and getter
	
    @Override
    public String toString(){
        return nama+" : "+alamat;
    }
}

next is creating a simple xml query, ContohMapper.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.edw.mybatis.mapper.ContohMapper" >

    <resultMap id="ContohMap" type="com.edw.mybatis.bean.Contoh" >
        <id column="nama" property="nama" jdbcType="VARCHAR" />
        <result column="alamat" property="alamat" jdbcType="VARCHAR" />
    </resultMap>
    

    <select id="selectAll" resultMap="ContohMap">
        SELECT * FROM contoh
    </select>

</mapper>

and an interface class to map my queries

package com.edw.mybatis.mapper;

import com.edw.mybatis.bean.Contoh;
import java.util.List;

public interface ContohMapper {    
    List<Contoh> selectAll();
}

Dont forget to create a connection pooling configuration on context.xml, which located under META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/MyBatisDBCP">
    
    <Resource name="jdbc/test" auth="Container"
            type="javax.sql.DataSource"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/test"
            username="root"
            password="xxxx"
            maxActive="100" maxIdle="30" maxWait="10000"
            removeAbandoned="true"
            removeAbandonedTimeout="60"
            logAbandoned="true"
            />
            
</Context>

an xml configuration, Configuration.xml. This is where i put my connection properties.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="data_source" value="java:/comp/env/jdbc/test"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/edw/mybatis/xml/ContohMapper.xml" />
    </mappers>
</configuration>

and a singleton class to load my configuration class,

package com.edw.mybatis.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/**
 *
 * @author edw
 */
public class MyBatisSqlSessionFactory {

    protected static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/mybatis/xml/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

and a simple servlet to call mybatis query

package com.edw.servlet;

import com.edw.mybatis.bean.Contoh;
import com.edw.mybatis.config.MyBatisSqlSessionFactory;
import com.edw.mybatis.mapper.ContohMapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class MainServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(MainServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();

            ContohMapper contohMapper = session.getMapper(ContohMapper.class);
            List<Contoh> contohs = contohMapper.selectAll();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>DBCP Example MainServlet</title>");
            out.println("</head>");
            out.println("<body>");
            
            for (Contoh contoh : contohs) {
                out.println(contoh.getNama()+" "+contoh.getAlamat()+"<br />");
                logger.debug(contoh.getNama()+" "+contoh.getAlamat());
            }

            out.println("</body>");
            out.println("</html>");

        }catch(Exception ex){
            logger.error(ex.getMessage(), ex);
            out.println(ex.getMessage());
        } finally {
            out.close();
        }
    } 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}

and dont forget to register your jndi and servlet to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Session -->
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <!-- Welcome file -->
    <welcome-file-list>
        <welcome-file>mainServlet</welcome-file>
    </welcome-file-list>

    <!--  Servlet -->
    <servlet>
        <servlet-name>mainServlet</servlet-name>
        <servlet-class>com.edw.servlet.MainServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>mainServlet</servlet-name>
        <url-pattern>/mainServlet</url-pattern>
    </servlet-mapping>

    <!-- JNDI -->
    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/test</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    
</web-app>

And also, dont forget to put your mysql-connector.jar to tomcat lib. And if you see this error, Cannot create JDBC driver of class '' for connect URL 'null', it means there’s something wrong with your JNDI configuration on context.xml.

This is my netbeans project screenshot

and this is what the result will look like

Have fun, cheers. (B)

Google+

Connecting a Servlet, iBatis and Glassfish 3

This time im trying to change my programming style, from a simple JDBC connection to a bit more complicated JDBC Connection Pool so i could increase my application’s response time. Btw, what is a Connection Pools? Basically, it’s a cached connections that are kept in a runtime object pool and can be used and reused as needed by the application. For a more complete explanation, you can check here.

Im planning to deploy my application on a Glassfish v3 and change my iBatis’ setting from simple JDBC to JNDI connection, but first i have create a MySql DataSource on m Glassfish. In order to create a connection pool, i put my MySQL JDBC Jar in <glassfish installation folder>/lib.

From my Glassfish console (http://localhost:4848/), i create a new Connection pools,

Start by giving its name, and selecting resource and database vendor type,

Connection type,

Dont forget adding these properties, so you can connect to your MySql Database,

you can test your connection by pinging it,

Btw, if you cant find the which resource type you need, here are some hints

  1. javax.sql.DataSource: is a non-pooled direct connection
  2. javax.sql.ConnectionPoolDataSource: connection is coming from pool
  3. javax.sql.XADataSource: is for distributed transactions

Create a new JDBC Resources using your new Connection Pool,

Next step is creating a simple web application using NetBeans 6.9. As usual, i create a simple table

CREATE DATABASE 'test'
USE 'test'

CREATE TABLE `contoh` (
  `nama` varchar(30) NOT NULL DEFAULT '',
  `alamat` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`nama`)
)

insert into contoh (nama, alamat) values ('edwin', 'jakarta');
insert into contoh (nama, alamat) values ('kamplenk', 'ciledug');
insert into contoh (nama, alamat) values ('nugie', 'pamulang');
insert into contoh (nama, alamat) values ('samsu', 'dago');
insert into contoh (nama, alamat) values ('tebek', 'jayapura');

next step is creating a java bean for database mapping

package com.edw.bean;

/**
 *
 * @author edw
 */
public class Contoh {

    private String nama;
    private String alamat;

    public Contoh(String nama, String alamat) {
        this.nama = nama;
        this.alamat = alamat;
    }

    public Contoh() {
    }

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    @Override
    public String toString() {
        return "Contoh{" + "nama=" + nama + " and alamat=" + alamat + '}';
    }        
}

and an xml mapping for database queries, i named it contoh.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="contoh" >

    <!--alias-->
    <typeAlias alias="Contoh" type="com.edw.bean.Contoh" />

    <resultMap id="result" class="Contoh">
        <result property="nama" column="NAMA" columnIndex="1"/>
        <result property="alamat" column="ALAMAT" columnIndex="2"/>
    </resultMap>

    <insert id="insertContoh" parameterClass="Contoh" >
    insert into contoh (nama, alamat)
    values (#nama:VARCHAR#, #alamat:VARCHAR#)
    </insert>

    <!--query select all-->
    <select id="selectAllContoh" resultMap="result">
    select nama, alamat
    from contoh
    </select>

    <!--query with Bean parameter-->
    <select id="selectContohWithPKfromBean" resultClass="Contoh" parameterClass="Contoh">
    select nama, alamat
    from contoh
    where nama like #nama:VARCHAR#
    </select>

    <!--query with String parameter-->
    <select id="selectContohWithPKfromString" resultClass="Contoh" parameterClass="java.lang.String">
    select nama, alamat
    from contoh
    where nama like #nama#
    </select>

    <!--query with Map parameter-->
    <select id="selectContohWithPKfromMap" resultClass="Contoh" parameterClass="java.util.Map">
    select nama, alamat
    from contoh
    where nama like #nama#
    </select>

</sqlMap>

and ibatis’ main xml configuration, sqlmapconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="JNDI">
            <property name="DataSource" value="mysqljndi"/>
        </dataSource>
    </transactionManager>

    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>
</sqlMapConfig>

next step is creating a simple java class to load all iBatis’ configuration file.

package com.edw.config;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.IOException;
import java.io.Reader;


/**
 *
 * @author edw
 */
public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (IOException e) {
            throw new RuntimeException("Fatal Error, ga dapet sqlmapconfignya.  Cause: " + e, e);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

a simple Servlet

package com.edw.servlet;

import com.edw.bean.Contoh;
import com.edw.config.SqlMapConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class Main extends HttpServlet {

    private Logger logger = Logger.getLogger(this.getClass());

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          
            out.println("<html>");
            out.println("<head>");
            out.println("<title>iBatis Test</title>");
            out.println("</head>");
            out.println("<body>");

            out.println("-----------------------");
            out.println("select all <br />");

            List<Contoh> contohs = SqlMapConfig.getSqlMap().queryForList("contoh.selectAllContoh");
            for (Contoh contoh : contohs) {
                out.println(contoh+"<br />");
            }

            out.println("<br />");
            out.println("<br />");
            
            out.println("-----------------------");
            out.println("select with Parameter Bean");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromBean", new Contoh("samsu", null))+"<br /><br />");

            out.println("-----------------------");
            out.println("select with Parameter String");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromString", "kamplenk")+"<br /><br />");

            out.println("-----------------------");
            out.println("select with Parameter Map");
            Map<String, String> map = new HashMap<String, String>();
            map.put("nama", "tebek");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromMap", map)+"<br /><br />");
            
            out.println("</body>");
            out.println("</html>");

        } catch(Exception ex){
            logger.error(ex.getMessage(),ex);
        } finally {
            out.close();
        }
    } 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
  
    @Override
    public String getServletInfo() {
        return "My Main Servlet";
    }
}

and my web.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Main</servlet-name>
        <servlet-class>com.edw.servlet.Main</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Main</servlet-name>
        <url-pattern>/Main</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>Main</welcome-file>
    </welcome-file-list>
</web-app>

this is the result on my browser when i run my application

this is my netbeans project structure

Again, i hope this simple tutorial could be useful for others. Cheers (B)
nb. im using Netbeans 6.9, iBatis 2.3.4 and Glassfish 3.

Google+

Connecting Remote EJB3 from a Servlet with WebLogic 10.3

Right now i’m trying to connect 2 different applications that located in a different server. Im using remote EJB3 to connecting them, with Apache Tomcat as server 1 and WebLogic 10.3 as server 2. Im using Netbeans 6.8 as primary IDE for this test.

create an EJB Module Project from Netbeans IDE, and create these files

first is the remote interface

package com.edw.ejb3;

import javax.ejb.Remote;

@Remote
public interface HelloEJBRemote {
    String sayHello(final String name);    
}

and the ejb implementation

package com.edw.ejb3;

import javax.ejb.Stateless;

@Stateless(mappedName="HelloEJB")
public class HelloEJB implements HelloEJBRemote {
    public String sayHello(final String name) {
        return "Hello "+name+" how do you do?";
    }
}

Package it as JAR or EAR, start Weblogic then use Admin Console (default: http://localhost:7001/ ) to deploy the EJB.
deployment

and to make sure, you can check EJB’s JNDI
ejb's jndi

next is creating a Web Project, dont forget to include your EJB project to your Web Project’s library.

create a servlet file to perform a connection to Remote EJBs.

package ejb;

import com.edw.ejb3.HelloEJBRemote;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EJBServlet extends HttpServlet {

    @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
            env.put(Context.PROVIDER_URL, "t3://localhost:7001");

            Context ic = new InitialContext(env);

            HelloEJBRemote remote = (HelloEJBRemote) ic.lookup("HelloEJB#com.edw.ejb3.HelloEJBRemote");

            out.println(remote.sayHello("Edwin"));

        } catch (Exception ex) {
            out.print(ex);
            ex.printStackTrace();
        } finally {
            out.close();
        }
    } 
}

and this is my web.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>EJBServlet</servlet-name>
        <servlet-class>ejb.EJBServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>EJBServlet</servlet-name>
        <url-pattern>/ejb</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

if you find this error,

javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory [Root exception is java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory]

it happen because you havent put wlfullclient.jar (WebLogic library) into your Apache Tomcat’s library folder. You can find it in your Weblogic installation folder ({weblogic}\server\lib) or you can create it your self, by executing wljarbuilder.jar.

java -jar wljarbuilder.jar

tomcat libs

you can test your app by running your web project from your IDE.
web content

this is my netbeans project structure
Netbeans Project Structure

Google+