一:JNDI配置方式
現(xiàn)在來(lái)講一下如何到服務(wù)器上對(duì) Data Source 進(jìn)行配置?
服務(wù)器: Tomcat 7
數(shù)據(jù)庫(kù):MySQL
1:將下面的代碼添加到Tomcat服務(wù)器上conf/context.xml中的<Context></Context>標(biāo)簽中
<Resource name="jdbc/shopping" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/shopping" />
上下文context.xml中的參數(shù)的解析如下:
其中的name屬性是數(shù)據(jù)源名稱,通常采取jdbc/**.
driverClassName屬性是驅(qū)動(dòng)程序名稱。
username,password,數(shù)據(jù)庫(kù)名稱和密碼
url:訪問(wèn)的數(shù)據(jù)庫(kù)路徑。其中url的內(nèi)容組成解析上篇博客中已經(jīng)分析
maxActive屬性是并發(fā)連接的最大數(shù)。設(shè)置為0則無(wú)限制。
maxWait屬性是等待連接的最大連接的時(shí)間。
maxIdle屬性是連接池中空閑的連接的個(gè)數(shù)。
2. 修改web.xml
打開%TOMCAT_HOME%\conf\web.xml,在</web-app>的前面添加以下內(nèi)容:
<description>MySQL Test App</description> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/shopping</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
3:建立測(cè)試文件
test.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <sql:query var="rs" dataSource="jdbc/shopping"> select id, name, normalprice from product </sql:query> <html> <head> <title>DB Test</title> </head> <body> <h2>Results</h2> <c:forEach var="row" items="${rs.rows}"> name ${row.name}<br/> normalprice ${row.normalprice}<br/> </c:forEach> </body> </html>
4.添加jar包
JDBC驅(qū)動(dòng)程序mysql-connector-java-5-bin.jar放置在%TOMCAT_HOME%\lib和應(yīng)用的WEB-INF\lib下,復(fù)制 jstl.jar 和 standard.jar 到 你的 WEB-INF/lib
目錄.
5:配置名稱name="jdbc/mldn"可以任意,配置完成后,需要通過(guò)名稱查找的方式,去找到數(shù)據(jù)源,本示例代碼運(yùn)用的Tomcat服務(wù)器,所以在查找時(shí)需要對(duì)名稱進(jìn)行定位:java:comp/env
<%@ page import="java.sql.*"%> <%@ page import="javax.sql.*"%> <%@ page import="javax.naming.*"%> <%! final String JNDINAME = "java:comp/env/jdbc/shopping" ; %> <% Connection conn = null ; try { // 初始化查找命名空間 Context ctx = new InitialContext() ; // 找到DataSource DataSource ds = (DataSource)ctx.lookup(JNDINAME) ; conn = ds.getConnection() ; } catch(Exception e) { System.out.println(e) ; } %> <%=conn%> <% // 將連接重新放回到池中 conn.close() ; %>
配置spring
配置spring <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"><value>java:comp/env/jdbc/xxx</value></property> </bean>