在jsp中如何获得数据源

在jsp中如何获得数据源
2024-11-21 16:51:21
推荐回答(1个)
回答1:

在jsp中获得数据源的方法是通过jdbc或者datasource连接到数据库然后获取得到。
1、jsp页面代码:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

"http://www.w3.org/TR/html4/loose.dtd">


content="text/html; charset=UTF-8">
测试数据库连接



连接成功!
连接失败!



2、在tomcat中配置
JDBCDemo context.xml


auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="root"
password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/demo?
useUnicode=true&characterEncoding=UTF8"/>

3、在java后台实现数据源的连接
import java.io.Serializable;import java.sql.*;
import javax.naming.*;
import javax.sql.DataSource;
public class DatabaseBean implements Serializable {
private DataSource dataSource;
public DatabaseBean() {
try {
Context initContext = new InitialContext();
Context envContext = (Context)
initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/demo");
} catch (NamingException ex) {
throw new RuntimeException(ex);
}
}
public boolean isConnectedOK() {
boolean ok = false;
Connection conn = null;
SQLException ex = null;
try {
conn = dataSource.getConnection();
if (!conn.isClosed()) {
ok = true;
}
} catch (SQLException e) {
ex = e;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
if(ex == null) {
ex = e;
}
}
}
if(ex != null) {
throw new RuntimeException(ex);
}
}
return ok;
}
}