环境
- tomcat9
- jdk8
- 数据库使用JNDI
tomcat9 配置 JNDI
https://blog.youkuaiyun.com/qq_26264237/article/details/90636085
项目结构
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>test jndi</description>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/sql</taglib-uri>
<taglib-location>/WEB-INF/sql.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
</jsp-config>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
- sql.tld和c.tld:测试jndi
- resource-ref:注册jndi
测试页面 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ 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/TestDB">
SELECT id, name FROM t_hello
</sql:query>
<html>
<head>
<title>DB Test</title>
</head>
<body>
<h2>Results</h2>
<c:forEach var="row" items="${rs.rows}">
[id: ${row.id} , name: ${row.name}]<br />
</c:forEach>
</body>
</html>
测试结果
http://localhost:8080/testJndiWeb/index.jsp
测试页面 index2.jsp
http://localhost:8080/testJndiWeb/index2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
request.setAttribute("ds", ds);
Connection conn = ds.getConnection();
Statement stt = conn.createStatement();
ResultSet rs = stt.executeQuery("SELECT id, name FROM t_hello");
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
while(rs.next()) {
Map<String, String> map = new HashMap<String, String>();
map.put("id", rs.getString(1));
map.put("name", rs.getString(2));
list.add(map);
}
conn.close();
conn = null;
request.setAttribute("list", list);
%>
<html>
<head>
<title>DB Test</title>
</head>
<body>
[ds=<c:out value="${ds }"></c:out>]<br/>
[list=<c:out value="${list }"></c:out>]<br/>
</body>
</html>