Kohei Nozaki's blog 

Defining Embedded Derby as a DataSource of Tomcat 8

Posted on Wednesday Feb 11, 2015 at 12:16AM in Technology


  1. Put derby.jar into $CATALINA_HOME/lib

  2. Define a Resource element inside Context element in $CATALINA_HOME/conf/context.xml as follows:

    <Resource name="jdbc/derby" auth="Container"
    		  username="sa" password="sa"
  3. Clone derby-shutdown-listener, exec mvn clean package and put target/derby-shutdown-listener.jar into $CATALINA_HOME/lib

  4. Put following fragment into Server element in $CATALINA_HOME/conf/server.xml

    <Listener className="org.nailedtothex.derby.DerbyShutdownLifecycleListener" />

Test of lookup from Servlet

  1. Put following fragment into WEB-INF/web.xml of your web application

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  2. Put an example Servlet as follows

    @WebServlet(urlPatterns = "/")
    public class TestServlet extends HttpServlet {
        private Context context;
        private DataSource dataSource;
        public void init() throws ServletException {
            try {
                context = new InitialContext();
                dataSource = (DataSource) context.lookup("java:comp/env/jdbc/derby");
            } catch (NamingException e) {
                throw new ServletException(e);
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try (Connection cn = dataSource.getConnection();
                 Statement st = cn.createStatement();
                 ResultSet rs = st.executeQuery("SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1")) {
                while (rs.next()) {
            } catch (SQLException e) {
                throw new ServletException(e);
        public void destroy() {
            if (context != null) {
                try {
                } catch (NamingException e) {
                    // no-op
  3. Access from your browser

No one has commented yet.

Leave a Comment

HTML Syntax: NOT allowed