1.在webapp下的META-INFO下新建文件context.xml
2.编辑context.xml
< Context path ="/test" docBase ="test" debug ="5" reloadable ="true" >
< Resource name ="jdbc/MySQL" auth ="Container" type ="javax.sql.DataSource"
factory ="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
driverClassName ="com.mysql.jdbc.Driver"
url ="jdbc:mysql://localhost:3306/你的DB名字"
username ="用户名" password ="密码"
maxActive ="20" maxIdle ="10" maxWait ="-1" />
</ Context >
![]()
此配置方法tomcat启动会将context.xml文件复制到tomcat conf\Catalina\localhost中,如后期不再需要,可以删除
3.重启tomcat
如果是使用全局Datasource
在server.xml中加入





The reference to entity "characterEncoding" must end with the ';' delimiter
数据源配置时加上编码转换格式后出问题了:
The reference to entity "characterEncoding" must end with the ';' delimiter
这个错误就是 context.xml中设置数据源链接URL的问题
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=UTF-8</param-value>
</context-param>
正确的如下:
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=UTF-8</param-value>
</context-param>
这大概是由xml文件中的编码规则决定要这么变换。
在xml文件中有以下几类字符要进行转义替换:
< | < | 小于号 |
> | > | 大于号 |
& | & | 和 |
' | ' | 单引号 |
" | " | 双引号 |
重复步骤 1,在context中加入
<ResourceLink global="你的JNDI名字" name="你的JNDI名字" type="javax.sql.DataSource"/>
如果是使用admin配置JNDI
Tomcat
+Service
+Host
+[要使用JNDI的文件夹]
+Resources
+Data Sources
接下来设定右边
下拉的选Data Sources Actions -> 选择 Create New Data Source
接下來设定
JNDI Name: jdbc/MySQL
Data Source URL: jdbc:mysql://localhost:3306/你的数据库名字
JDBC Driver Class: com.mysql.jdbc.Driver
User Name: 用户名
Password: 密码
接著按 Save
最後按上方 Commit Changes 按鈕就可以了
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class DB extends HttpServlet {
DataSource pool;
public void init() throws ServletException {
Context context = null;
try {
context = (Context)new InitialContext();
pool = (DataSource)context.lookup("java:comp/env/jdbc/MySQL");
if(pool == null) throw new ServletException ("mysqlis an unknow DataSource");
}
catch(NamingException ne) {
throw new ServletException(ne.getMessage());
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response )throws ServletException,java.io.IOException {
String sql = "select * from test";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rsm = null;
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println("<html><head><title>Database Access</title></head><body>");
try{
conn = pool.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
rsm = rs.getMetaData();
out.println("<table border=1><tr>");
int colCount = rsm.getColumnCount();
for(int i = 1;i <=colCount; ++i) {
out.println("<td>"+rsm.getColumnName(i)+"</td>");
}
out.println("</tr><br>");
while(rs.next()) {
out.println("<tr>");
for(int i = 1;i<=colCount; ++i)
out.println("<td>"+rs.getXXX(i); + "</td>");
out.println("</tr>");
}
}
catch(Exception e) {
throw new ServletException(e.getMessage());
}
finally {
try{
if(stmt != null)
stmt.close();
if(conn != null)
conn.close();
}
catch(SQLException sqle) {
}
}
out.println("</table></body></html>");
}
}
封装后代码:
package com.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
*
* @author Administrator 连接数据库
*/
public class Utils {
public static String driver = "";
public static String url = "";
public static String user = "";
public static String pwd = "";
private static Connection dbCon = null;
private static Utils utils = null;
private static DataSource pool;
public static Utils getInstance(){
if (utils == null){
utils = new Utils();
}
return utils;
}
/**
* jdbc文件设置参数 路径 用户 密码
*
* @return
* @throws Exception
*/
public DataSource getDataSource() throws Exception {
Context context = null;
context = (Context)new InitialContext();
pool = (DataSource)context.lookup("java:comp/env/jdbc/mytest");
return pool;
}
public Connection getConn() throws Exception {
pool = getDataSource();
if(pool == null) {
throw new Exception ("mysql is an unknow DataSource");
}
return pool.getConnection();
}
// /**
// * jdbc文件设置参数 路径 用户 密码
// *
// * @return
// * @throws Exception
// */
// public Connection getConn() throws Exception {
// Properties dbProps = new Properties();
// InputStream is = getClass().getResourceAsStream("/db.properties");
// dbProps.load(is);
// driver = dbProps.getProperty("driver");
// url = dbProps.getProperty("url");
// user = dbProps.getProperty("user");
// pwd = dbProps.getProperty("pwd");
// Class.forName(driver);
// dbCon = DriverManager.getConnection(url, user, pwd);
// return dbCon;
// }
/**
* 关闭连接的通道 数据库
*
* @param conn
* @param ret
* @param pst
*/
public void close(Connection conn, ResultSet ret, PreparedStatement pst) {
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ret != null) {
try {
ret.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭连接的通道 数据库
*
* @param conn
* @param ret
* @param smt
*/
public void close(Connection conn, ResultSet ret, Statement smt) {
if (smt != null) {
try {
smt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ret != null) {
try {
ret.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}