import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class ExploreImplicitObjects {
static class MiniJspWriter {
private final StringBuilder buffer = new StringBuilder();
private final StringBuilder flushed = new StringBuilder();
private final boolean buffered;
MiniJspWriter(boolean buffered) { this.buffered = buffered; }
public void print(Object v) throws IOException {
if (buffered) buffer.append(v);
else flushed.append(v);
}
public void println(Object v) throws IOException {
print(v);
print("\n");
}
public void flush() throws IOException {
flushed.append(buffer);
buffer.setLength(0);
}
public String getFlushed() { return flushed.toString(); }
public int getBufferedLength() { return buffer.length(); }
}
static class MiniPageContext {
static final int PAGE_SCOPE = 1;
static final int REQUEST_SCOPE = 2;
static final int SESSION_SCOPE = 3;
static final int APPLICATION_SCOPE = 4;
private final Map<Integer, Map<String, Object>> scopes = new LinkedHashMap<>();
MiniPageContext(Map<String, Object> req, Map<String, Object> sess, Map<String, Object> app) {
scopes.put(PAGE_SCOPE, new LinkedHashMap<>());
scopes.put(REQUEST_SCOPE, req);
scopes.put(SESSION_SCOPE, sess);
scopes.put(APPLICATION_SCOPE, app);
}
void setAttribute(String name, Object val, int scope) { scopes.get(scope).put(name, val); }
Object getAttribute(String name, int scope) { return scopes.get(scope).get(name); }
void removeAttribute(String name, int scope) { scopes.get(scope).remove(name); }
void removeAttribute(String name) {
for (Map<String, Object> m : scopes.values()) m.remove(name);
}
}
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<>();
// Case 1: nine_implicit_objects_inventory
Map<String, String> implicitTypes = new LinkedHashMap<>();
implicitTypes.put("request", "javax.servlet.http.HttpServletRequest");
implicitTypes.put("response", "javax.servlet.http.HttpServletResponse");
implicitTypes.put("out", "javax.servlet.jsp.JspWriter");
implicitTypes.put("session", "javax.servlet.http.HttpSession");
implicitTypes.put("application", "javax.servlet.ServletContext");
implicitTypes.put("config", "javax.servlet.ServletConfig");
implicitTypes.put("pageContext", "javax.servlet.jsp.PageContext");
implicitTypes.put("page", "java.lang.Object");
implicitTypes.put("exception", "java.lang.Throwable");
Map<String, Object> exp1 = new LinkedHashMap<>();
exp1.put("count", 9);
exp1.put("exception_type", "java.lang.Throwable");
exp1.put("out_type", "javax.servlet.jsp.JspWriter");
Map<String, Object> act1 = new LinkedHashMap<>();
act1.put("count", implicitTypes.size());
act1.put("exception_type", implicitTypes.get("exception"));
act1.put("out_type", implicitTypes.get("out"));
addCase(cases, "nine_implicit_objects_inventory",
"核对 JSP 九大隐式对象名称与标准接口/类类型映射(明确 exception 为小写变量且类型为 Throwable)。",
exp1, act1);
// Case 2: request_response_out_buffering + Case 3: session_and_application_scopes
Map<String, Object> applicationAttrs = new LinkedHashMap<>();
Map<String, Map<String, Object>> sessions = new LinkedHashMap<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
server.createContext("/implicit.jsp", (HttpExchange ex) -> {
String sid = ex.getRequestHeaders().getFirst("X-Session-Id");
if (sid == null) sid = "S1";
Map<String, Object> sess = sessions.computeIfAbsent(sid, k -> new LinkedHashMap<>());
int userHits = ((Integer) sess.getOrDefault("hits", 0)) + 1;
sess.put("hits", userHits);
int appHits = ((Integer) applicationAttrs.getOrDefault("totalHits", 0)) + 1;
applicationAttrs.put("totalHits", appHits);
MiniJspWriter out = new MiniJspWriter(true);
out.print("method=" + ex.getRequestMethod() + ";");
out.println("sess=" + sid + ":" + userHits + ";app=" + appHits);
out.flush();
byte[] body = out.getFlushed().getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
ex.getResponseHeaders().set("X-Implicit-Checked", "true");
ex.sendResponseHeaders(200, body.length);
try (OutputStream os = ex.getResponseBody()) { os.write(body); }
});
server.start();
int port = server.getAddress().getPort();
// Buffered vs unbuffered out writer check
MiniJspWriter bufferedOut = new MiniJspWriter(true);
bufferedOut.print("A");
int pendingBeforeFlush = bufferedOut.getBufferedLength();
bufferedOut.println(42);
bufferedOut.flush();
MiniJspWriter unbufferedOut = new MiniJspWriter(false);
unbufferedOut.print("B");
HttpURLConnection c1 = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/implicit.jsp").openConnection();
c1.setRequestProperty("X-Session-Id", "U1");
String r1 = readBody(c1);
String hdrChecked = c1.getHeaderField("X-Implicit-Checked");
c1.disconnect();
HttpURLConnection c2 = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/implicit.jsp").openConnection();
c2.setRequestProperty("X-Session-Id", "U1");
String r2 = readBody(c2);
c2.disconnect();
HttpURLConnection c3 = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/implicit.jsp").openConnection();
c3.setRequestProperty("X-Session-Id", "U2");
String r3 = readBody(c3);
c3.disconnect();
Map<String, Object> exp2 = new LinkedHashMap<>();
exp2.put("pending_before_flush", 1);
exp2.put("buffered_flushed", "A42\n");
exp2.put("unbuffered_immediate", "B");
exp2.put("response_header", "true");
exp2.put("request_method_echo", "method=GET;sess=U1:1;app=1");
Map<String, Object> act2 = new LinkedHashMap<>();
act2.put("pending_before_flush", pendingBeforeFlush);
act2.put("buffered_flushed", bufferedOut.getFlushed());
act2.put("unbuffered_immediate", unbufferedOut.getFlushed());
act2.put("response_header", hdrChecked);
act2.put("request_method_echo", r1.trim());
addCase(cases, "request_response_out_buffering",
"验证 request 方法读取、response 自定义响应头设置以及 out 对象的 print/println/flush 缓冲与非缓冲行为。",
exp2, act2);
Map<String, Object> exp3 = new LinkedHashMap<>();
exp3.put("u1_second_hit", "method=GET;sess=U1:2;app=2");
exp3.put("u2_first_hit_shared_app", "method=GET;sess=U2:1;app=3");
Map<String, Object> act3 = new LinkedHashMap<>();
act3.put("u1_second_hit", r2.trim());
act3.put("u2_first_hit_shared_app", r3.trim());
addCase(cases, "session_and_application_scopes",
"对比多客户端回环请求下 session(按用户隔离)与 application(全应用共享)作用域属性状态。",
exp3, act3);
} finally {
server.stop(0);
}
// Case 4: config_and_servlet_name
String webXml = "<web-app><servlet><servlet-name>DemoJspServlet</servlet-name>"
+ "<init-param><param-name>dataPath</param-name><param-value>/var/data</param-value></init-param>"
+ "</servlet></web-app>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(webXml.getBytes(StandardCharsets.UTF_8)));
String servletName = doc.getElementsByTagName("servlet-name").item(0).getTextContent().trim();
String paramVal = doc.getElementsByTagName("param-value").item(0).getTextContent().trim();
Map<String, Object> exp4 = new LinkedHashMap<>();
exp4.put("servlet_name", "DemoJspServlet");
exp4.put("init_param_dataPath", "/var/data");
Map<String, Object> act4 = new LinkedHashMap<>();
act4.put("servlet_name", servletName);
act4.put("init_param_dataPath", paramVal);
addCase(cases, "config_and_servlet_name",
"解析 web.xml 并验证 config.getServletName() 与初始化参数读取。",
exp4, act4);
// Case 5: pagecontext_scopes_page_and_exception
Map<String, Object> reqScope = new LinkedHashMap<>();
Map<String, Object> sessScope = new LinkedHashMap<>();
Map<String, Object> appScope = new LinkedHashMap<>();
MiniPageContext pc = new MiniPageContext(reqScope, sessScope, appScope);
pc.setAttribute("attrName", "P", MiniPageContext.PAGE_SCOPE);
pc.setAttribute("attrName", "R", MiniPageContext.REQUEST_SCOPE);
pc.setAttribute("attrName", "S", MiniPageContext.SESSION_SCOPE);
pc.setAttribute("attrName", "A", MiniPageContext.APPLICATION_SCOPE);
// 2-arg removeAttribute removes ONLY PAGE_SCOPE
pc.removeAttribute("attrName", MiniPageContext.PAGE_SCOPE);
boolean pageGoneReqStays = pc.getAttribute("attrName", MiniPageContext.PAGE_SCOPE) == null
&& "R".equals(pc.getAttribute("attrName", MiniPageContext.REQUEST_SCOPE));
// 1-arg removeAttribute removes across ALL scopes
pc.removeAttribute("attrName");
boolean allGone = pc.getAttribute("attrName", MiniPageContext.REQUEST_SCOPE) == null
&& pc.getAttribute("attrName", MiniPageContext.SESSION_SCOPE) == null
&& pc.getAttribute("attrName", MiniPageContext.APPLICATION_SCOPE) == null;
Object currentPageInstance = new ExploreImplicitObjects();
Object pageAlias = currentPageInstance;
Throwable exceptionObj = new IllegalStateException("模拟前置页面异常");
Map<String, Object> exp5 = new LinkedHashMap<>();
exp5.put("two_arg_remove_only_page", true);
exp5.put("one_arg_remove_all_scopes", true);
exp5.put("page_is_this_alias", true);
exp5.put("exception_message", "模拟前置页面异常");
Map<String, Object> act5 = new LinkedHashMap<>();
act5.put("two_arg_remove_only_page", pageGoneReqStays);
act5.put("one_arg_remove_all_scopes", allGone);
act5.put("page_is_this_alias", pageAlias == currentPageInstance);
act5.put("exception_message", exceptionObj.getMessage());
addCase(cases, "pagecontext_scopes_page_and_exception",
"实测 pageContext 四级作用域的 removeAttribute(name, PAGE_SCOPE) 与 removeAttribute(name) 差异、page 即 this 以及 exception 异常封装。",
exp5, act5);
Map<String, Object> root = new LinkedHashMap<>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
private static String readBody(HttpURLConnection conn) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
}
return sb.toString();
}
private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", Objects.equals(expected, actual));
cases.add(c);
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) {
String s = (String) obj;
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
else sb.append(ch);
}
}
return sb.append("\"").toString();
}
if (obj instanceof List) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(",");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(",");
first = false;
sb.append(toJson(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return toJson(obj.toString());
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/jsp-implicit-objects-lab/ExploreImplicitObjects.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreImplicitObjects.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1404.zip
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1388.zip