2013. 8. 21. 10:16 java coffee
JNDI with Spring
#Environment
STS, Tomcat 7.0, Mysql
1. Tomcat setting in Server
- server.xml
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container"
defaultAutoCommit="false"
driverClassName="com.mysql.jdbc.Driver"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
initialSize="10" maxActive="100" maxWait="10000" minIdle="10"
name="jdbc/afterrainDS"
username="afterrain"
password="afterrain"
type="javax.sql.DataSource"
url="jdbc:mysql://127.0.0.1:3306/afterrain"
validationQuery="SELECT 1 FROM DUAL"/>
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
...
...
<Context docBase="AfterRainJ" path="/openapp" reloadable="true" source="org.eclipse.jst.jee.server:AfterRainJ">
<ResourceLink global="jdbc/afterrainDS" name="jdbc/afterrainDS" type="javax.sql.DataSource" />
</Context>
2. Spring bean register
- root-context.xml
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/jdbc/afterrainDS" />
</bean>
3. Test JSP
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ page session="false" %>
<sql:query var="rs" dataSource="jdbc/afterrainDS">
select comp_name, phone, fax, address, gen_usr_no from company
</sql:query>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
<h2>Query Results</h2>
<c:forEach var="row" items="${rs.rows}">
Comp_name ${row.comp_name}<br/>
Phone ${row.phone}<br/>
Fax ${row.fax}<br/>
Address ${row.address}<br/>
Gen_usr_no ${row.gen_usr_no}<br/>
</c:forEach>
</body>
</html>