1. Database Configuration
Create a new test user, a new database and a single test table. Your MySQL User must has a password assigned. The driver would fail if you try to connect with an empty password.
GRANT All Privileges on *.* toJavauser@localhostidentified by 'Javadude' with GRANT OPTION;CREATE DATABASEjavatest; Usejavatest;CREATE TABLEtestdata (IDINT not NULLAuto_incrementPRIMARY KEY, fooVARCHAR( -), BarINT);INSERT intoTestDataVALUES(NULL,'Hello',12345);
2. Context Configuration
Configure the JNDI DataSource in Tomcat is adding a declaration for your resource to your Context.
<Resourcename= "Jdbc/testdb"Auth= "Container"type= "Javax.sql.DataSource"maxactive= "+"Maxidle= "+"maxwait= "10000"username= "Javauser"Password= "Javadude"Driverclassname= "Com.mysql.jdbc.Driver"URL= "Jdbc:mysql://localhost:3306/javatest"/>
3. Web. XML configuration
Now create a for this WEB-INF/web.xml
test application.
<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "2.5"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <Resource-ref> <Description>DB Connection</Description> <Res-ref-name>Jdbc/testdb</Res-ref-name> <Res-type>Javax.sql.DataSource</Res-type> <Res-auth>Container</Res-auth> </Resource-ref></Web-app>
4. Test Code
Now, create a simple page for use test.jsp
later.
<%@ taglib URI="Http://java.sun.com/jsp/jstl/sql"prefix="SQL"%><%@ taglib URI="Http://java.sun.com/jsp/jstl/core"prefix="C"%><Sql:queryvar= "RS"DataSource= "Jdbc/testdb">Select ID, foo, bar from TestData</Sql:query><HTML> <Head> <title>DB Test</title> </Head> <Body> <H2>Results</H2> <C:foreachvar= "Row"Items= "${rs.rows}">Foo ${row.foo}<BR/>Bar ${row.bar}<BR/> </C:foreach> </Body></HTML>
TOMCAT-DBCP Configuration