縱觀網上,在TOMCAT中進行配置的文章非常多,而專門寫如何在項目中進行配置的文章很少。那麼,如何在項目中進行配置呢。
大家都知道,Eclipse是會自動將項目放在workspace之中。有人說,那麼就對WORKSPACE中的.SERVER進行配置,然後再對項目進行配置。然而,不知是否是RP問題,筆者只要對.SERVER下的server.xml進行配置,運行tomcat就會報錯。
所以,我們就單獨在項目裡面進行配置。
首先,在workspace/項目名/WEBCONTENT/META-INF下建立context.xml,內容為:
<?xml version='1.0' encoding='utf-8'?> <Context> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/sqlserver" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="sa" password="*******" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=book" /> <ResourceLink name="jdbc/sqlserver" global="jdbc/sqlserver" type="javax.sql.DataSource"/> </Context>
然後,修改workspace/項目名/WEBCONTENT/WEB-INF下的web.xml為:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>MyDemo1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <resource-ref> <description /> <res-ref-name>jdbc/sqlserver</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app>
然後,再寫一個JSP頁面測試,index.jsp
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <%@page import="java.sql.*,javax.sql.*,javax.naming.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>Insert title here</title> </head> <body> <% Connection conn=null; try { InitialContext ctx=new InitialContext(); DataSource ds=(DataSource)ctx.lookup("java:/comp/env/jdbc/sqlserver"); conn=ds.getConnection(); if(conn!=null) { out.println("資料來源配置正確"); } } catch(Exception ex) { out.println(ex.getMessage()); } %> </body> </html>
記住,要將串連MS SQLSERVER的三個驅動包放於項目的lib下以及TOMCAT 6.0的LIB下。