import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ExploreDatabaseAccess {
static class WebsiteRow {
final int id;
final String name;
final String url;
final int alexa;
final String country;
WebsiteRow(int id, String name, String url, int alexa, String country) {
this.id = id;
this.name = name;
this.url = url;
this.alexa = alexa;
this.country = country;
}
}
static class TrackedResource implements AutoCloseable {
final String label;
final List<String> closedLog;
TrackedResource(String label, List<String> closedLog) {
this.label = label;
this.closedLog = closedLog;
}
@Override
public void close() {
closedLog.add(label);
}
}
static String esc(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
}
return sb.toString();
}
static String caseJson(String name, String summary, String expected, String actual) {
boolean passed = expected.equals(actual);
return " {\"name\": \"" + esc(name) + "\", \"summary\": \"" + esc(summary)
+ "\", \"expected\": \"" + esc(expected) + "\", \"actual\": \"" + esc(actual)
+ "\", \"passed\": " + passed + "}";
}
public static void main(String[] args) throws Exception {
final List<WebsiteRow> websites = Arrays.asList(
new WebsiteRow(1, "Google", "https://www.google.com/", 1, "USA"),
new WebsiteRow(2, "Taobao", "https://www.taobao.com/", 13, "CN"),
new WebsiteRow(3, "BlueSky Docs", "https://example.org/docs/", 5892, ""),
new WebsiteRow(4, "Weibo", "https://weibo.com/", 20, "CN"),
new WebsiteRow(5, "Facebook", "https://www.facebook.com/", 3, "USA")
);
List<String> cases = new ArrayList<String>();
// Case 1: Schema DDL columns and 5 seed rows
List<String> cols = Arrays.asList("id", "name", "url", "alexa", "country");
int cnCount = 0;
for (WebsiteRow row : websites) {
if ("CN".equals(row.country)) {
cnCount++;
}
}
String act1 = "cols=" + cols.size() + "|rows=" + websites.size() + "|cnCount=" + cnCount + "|first=" + websites.get(0).name;
String exp1 = "cols=5|rows=5|cnCount=2|first=Google";
cases.add(caseJson("websites_schema_and_seed_rows", "验证 websites 演示表 5 列结构与 5 条示例记录", exp1, act1));
// Case 2: JDK 8 java.sql interfaces, JDBC URL parsing, and missing external driver check
boolean jdbcApiPresent = Connection.class.isInterface()
&& Statement.class.isInterface()
&& PreparedStatement.class.isInterface()
&& ResultSet.class.isInterface()
&& SQLException.class.getSuperclass() == Exception.class
&& DriverManager.class != null;
String jdbcUrl = "jdbc:mysql://localhost:3306/app_demo?useSSL=false&characterEncoding=UTF-8";
URI innerUri = URI.create(jdbcUrl.substring("jdbc:".length()));
boolean driverMissing;
try {
Class.forName("com.mysql.jdbc.Driver");
driverMissing = false;
} catch (ClassNotFoundException ex) {
driverMissing = true;
}
String act2 = "jdbcApi=" + jdbcApiPresent
+ "|subprotocol=" + innerUri.getScheme()
+ "|host=" + innerUri.getHost()
+ "|port=" + innerUri.getPort()
+ "|db=" + innerUri.getPath().substring(1)
+ "|driverNotInStdlib=" + driverMissing;
String exp2 = "jdbcApi=true|subprotocol=mysql|host=localhost|port=3306|db=app_demo|driverNotInStdlib=true";
cases.add(caseJson("jdbc_url_driver_and_result_flow", "验证 JDK 8 java.sql 接口、MySQL JDBC URL 解析与未放驱动 JAR 时的 ClassNotFoundException", exp2, act2));
// Case 3: Deterministic reverse resource close order (ResultSet -> Statement -> Connection)
List<String> closeOrder = new ArrayList<String>();
try (TrackedResource conn = new TrackedResource("Connection", closeOrder);
TrackedResource stmt = new TrackedResource("Statement", closeOrder);
TrackedResource rs = new TrackedResource("ResultSet", closeOrder)) {
if (conn == null || stmt == null || rs == null) {
throw new IllegalStateException("unexpected null");
}
}
String act3 = closeOrder.toString();
String exp3 = "[ResultSet, Statement, Connection]";
cases.add(caseJson("jdbc_resource_close_order", "验证 ResultSet -> Statement -> Connection 逆序安全释放", exp3, act3));
// Case 4: HTTP rendering of SELECT id, name, url FROM websites
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/DatabaseAccess", (HttpExchange ex) -> {
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE html><html><head><title>Servlet JDBC</title></head><body>");
for (WebsiteRow r : websites) {
html.append("ID: ").append(r.id)
.append(", 站点名称: ").append(r.name)
.append(", 站点 URL: ").append(r.url)
.append("<br />");
}
html.append("</body></html>");
byte[] bytes = html.toString().getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
ex.sendResponseHeaders(200, bytes.length);
OutputStream os = ex.getResponseBody();
os.write(bytes);
os.close();
});
server.start();
try {
int port = server.getAddress().getPort();
HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/DatabaseAccess").openConnection();
int code = conn.getResponseCode();
String ctype = conn.getContentType();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String body = br.readLine();
br.close();
conn.disconnect();
int brCount = body.split("<br />", -1).length - 1;
boolean hasFirstAndLast = body.contains("ID: 1, 站点名称: Google") && body.contains("ID: 5, 站点名称: Facebook");
String act4 = "status=" + code + "|utf8=" + (ctype != null && ctype.contains("UTF-8"))
+ "|renderedRows=" + brCount + "|hasFirstAndLast=" + hasFirstAndLast;
String exp4 = "status=200|utf8=true|renderedRows=5|hasFirstAndLast=true";
cases.add(caseJson("http_database_html_rendering", "通过本地 HttpServer 实测查询结果 HTML 渲染与 UTF-8 响应头", exp4, act4));
} finally {
server.stop(0);
}
System.out.println("{");
System.out.println(" \"version\": \"Eclipse Adoptium OpenJDK " + esc(System.getProperty("java.version")) + "\",");
System.out.println(" \"cases\": [");
for (int i = 0; i < cases.size(); i++) {
System.out.println(cases.get(i) + (i + 1 < cases.size() ? "," : ""));
}
System.out.println(" ]");
System.out.println("}");
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/servlet-database-access-lab/ExploreDatabaseAccess.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreDatabaseAccess.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1365.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a1361.zip