星期四, 3月 27, 2014

Minimum JNDI-JDBC requirement

在 Eclipse + Tomcat,做一個最小需求的 JNDI JDBC 連線測試環境:
  1. sqlite jdbc jar
  2. context.xml
  3. web.xml
  4. 部署位置
  5. NewFile.jsp
<%@ page import="java.util.*" %>  
<%@ page import="java.sql.*" %>  
<%@ page import="javax.sql.*" %>  
<%@ page import="javax.naming.*" %>  
<%@ page language="java" contentType="text/html;charset=UTF-8" %>  
<%
Object o = session.getAttribute("m");
HashMap<String, Connection> m = null;
if (o == null) {
m = new HashMap<String, Connection>();
}
else {
m = (HashMap<String, Connection>)o;
}
  Connection con = null;
  try {
  Context initContext = new InitialContext();
  if (initContext == null) {
  out.println("initContext null");
  } else {
  Context envContext = (Context) initContext.lookup("java:/comp/env");
  if (envContext == null) {
  out.println("envContext null");
  } else {
  DataSource ds = (DataSource) envContext.lookup("jdbc/myDataSource");
  if (ds == null) {
  out.println("ds null");
  } else {
  // get connection
  String parameterGet = request.getParameter("get");
  if (parameterGet == null) {
  }
  else {
  int newCount = m.size() + 1;
  while (true) {
  con = ds.getConnection();
    String connectionId = String.valueOf(con.hashCode());
    m.put(connectionId, con);
    if (m.size() == newCount) {
      session.setAttribute("m", m);
    break;
    }
  }
  }
  // close connection
  String parameterClose = request.getParameter("close");
  String pool = request.getParameter("pool");
  if (parameterClose == null || pool == null) {
  }
  else {
  Iterator<Map.Entry<String, Connection>> iter = m.entrySet().iterator();
  while (iter.hasNext()) {
      Map.Entry<String, Connection> entry = (Map.Entry<String, Connection>) iter.next();
      String key = entry.getKey();
if (key.equals(pool)) {
m.remove(key);
session.setAttribute("m", m);
break;
}
  }
  }
  }
  }
  }
  } catch (SQLException sqle) {
  out.println("sqle=" + sqle);
  } finally {
  if (con == null) {
  } else {
  con.close();
  con = null;
  }
  }
  %>  

<!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=US-ASCII">
<title>Insert title here</title>
</head>
<body>
<form>
<div>Connection Pool:</div>
<select name="pool" size="10">
<%
Iterator<Map.Entry<String, Connection>> iter = m.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String, Connection> entry = (Map.Entry<String, Connection>) iter.next();
    String key = entry.getKey();
    out.println("<option>" + key + "</option>");
}
%>
</select>
<div>
<input type="submit" name="get" value="get" />
<input type="submit" name="close" value="close" />
</div>
</form>
</body>

</html>

沒有留言:

張貼留言