Question

How can I bind Datasource to an attribute in ServletContext in a Java web application, and how can I use it to query database?

Was it helpful?

Solution

First you will need a context.xml in the root/META-INF folder, an example:

<Context>
    <Resource name="jdbc/superblog" auth="Container" type="javax.sql.DataSource"
              maxActive="50" maxIdle="30" maxWait="10000"
              username="username" password="passwordhere"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/superblog?useEncoding=true&amp;characterEncoding=UTF-8"
              URIEncoding="UTF-8"/>
</Context>

And then in web.xml:

<resource-ref>
    <description>MySQL Datasource example</description>
    <res-ref-name>jdbc/superblog</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

Now let's put it in the ServletContext:

package com.tugay.listeners;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

public class ServletContextListenerForDataSource
        implements ServletContextListener {

    @Resource(name = "jdbc/superblog")
    DataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().setAttribute("datasource", dataSource);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

Great now let's use it in a Servlet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Super Blog</title>
</head>
<body>
<div>
    <form method="POST" action="${pageContext.servletContext.contextPath}/submit"
          accept-charset="utf-8">
        <label for="name">Name please:
            <input type="text" id="name" name="name"/>
        </label>
        <input type="submit" id="submit" value="Send it!">
    </form>
</div>
</body>
</html>

Assume this form is posted to the following Servlet:

package com.tugay.listeners;

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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class MyFormServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {

        final String name = httpServletRequest.getParameter("name");
        final DataSource datasource
                = (DataSource) getServletContext().getAttribute("datasource");
        try {
            final Connection connection = datasource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + "app_user" + "(username) VALUES(?)");
            preparedStatement.setString(1, name);
            preparedStatement.execute();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

This is it, hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top