How do I create a Data Source object for JdbcTemplate?

In this example you will learn how to create and configure a DriverManagerDataSource object that will be used by the JdbcTemplate object. There are some information required when creating a DataSource including the JDBC driver class, the JDBC Url of the target database, the username and password for connecting to database server.

package org.kodejava.example.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.List;

public class DataSourceDemo {
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String JDBC_URL = "jdbc:mysql://localhost/mediadb";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "";

    public static void main(String[] args) {
        // Creates an instance of DriverManagerDataSource and pass
        // it to the JdbcTemplate.
        DataSource source = getDataSource();
        JdbcTemplate template = new JdbcTemplate(source);

        // After creating a template with a data source inject we
        // can do a database manipulation such as the CRUD operation.
        System.out.println("DataSource = " + template.getDataSource());
        List records = template.queryForList("SELECT * FROM records");
        for (int i = 0; i < records.size(); i++) {
            System.out.println("Records = " + records.get(i));
        }
    }

    /**
     * Returns a DataSource object for connection to the database.
     *
     * @return a DataSource.
     */
    private static DataSource getDataSource() {
        // Creates a new instance of DriverManagerDataSource and sets
        // the required parameters such as the Jdbc Driver class,
        // Jdbc URL, database user name and password.
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DataSourceDemo.DRIVER);
        dataSource.setUrl(DataSourceDemo.JDBC_URL);
        dataSource.setUsername(DataSourceDemo.USERNAME);
        dataSource.setPassword(DataSourceDemo.PASSWORD);
        return dataSource;
    }
}

How do I use JNDI to get database connection or data source?

package org.kodejava.example.jndi;

import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JNDITestServlet extends HttpServlet implements Servlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        // This implementation of doGet method show us an example to use
        // conn obtained in the getConnection() method.
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy");

        res.setContentType("text/html");
        PrintWriter writer = res.getWriter();

        Connection conn = getConnection();
        if (conn != null) {
            try {
                // A query to get current date time from Oracle database
                String sql = "SELECT SYSDATE FROM DUAL";
                PreparedStatement statement = conn.prepareStatement(sql);
                ResultSet rs = statement.executeQuery();

                while (rs.next()) {
                    Date date = rs.getDate("SYSDATE");
                    writer.println("The current date is " + format.format(date));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (!conn.isClosed()) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Get a database connection from the registered data source in the 
     * servlet container. To registered the JNDI data source you should 
     * refer to your servlet container documentation.
     *
     * @return a database connection
     */
    private Connection getConnection() {
        Connection connection = null;
        try {
            InitialContext context = new InitialContext();
            DataSource dataSource = (DataSource) context
                    .lookup("jdbc/DataSource");
            connection = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
}