If you are using Apache Tomcat 7, you can use @Resource
in a servlet for inject the datasource.
Add the file context.xml
in the META-INF
directory, local to the project:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/TestResource">
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password=""
url="jdbc:mysql://localhost:3306/test"
maxActive="100"
maxIdle="30"
maxWait="10000"/>
</Context>
In the servlet:
@WebServlet(urlPatterns = { "/" }, loadOnStartup = 0)
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource(name = "jdbc/test")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
try (Connection conn = ds.getConnection();
PrintWriter out = resp.getWriter();) {
out.println(conn.getMetaData().getDatabaseProductName());
out.println(conn.getMetaData().getDatabaseProductVersion());
} catch (SQLException e) {
log(e.getMessage(), e);
}
}
}
The WAR structure is as following:
C:.
+---META-INF
| context.xml
| MANIFEST.MF
|
\---WEB-INF
+---classes
| \---test
| TestServlet.class
|
\---lib
mysql.jar
The output for this in browser http://localhost:8080/Test/
:
MySQL
5.5.32