Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Configuration JNDI DataSource for MySQL

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 209
    Comment on it

    JNDI DataSource Configuration This blog is written with the aim to show JNDI DataSource configuration for a web container like tomcat.
    JNDI stands for Java Naming and Directory Interface, a directory service provided for java-based client applications to search and look up objects with names.
    DataSource is a name to the connection setup to a database on a server.
    In this blog, we are going to setup JNDI DataSource for MySQL database.

    Create a Sample Database

    I have created following database and table inside.

    create database usersdb;
    
    use usersdb;
    
    CREATE TABLE `users` (
      `user_id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(45) NOT NULL,
      `password` varchar(45) NOT NULL,
      `email` varchar(45) NOT NULL,
      PRIMARY KEY (`user_id`)
    );
    

    Configure Tomcat context

    Add the Resource in Context.xml in $CATALINA_BASE/conf/context.xml

    <Resource
        name="jdbc/UsersDB"
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="100"
        maxIdle="30"
        maxWait="10000"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/usersdb"
        username="root"
        password=""
        />
    

    Configure web.xml

    Add the following resource-ref in your project's web.xml

    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/UsersDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    


    Now the JNDI DataSource configured for your application. You can have the DataSource as following -

    InitialContext context = new InitialContext();
    Context envContext = (Context) context.lookup("java:comp/env");
    DataSource dataSource = (DataSource) envContext.lookup("jdbc/UsersDB");
    

    Thanks.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: