JSP 客户端请求
讲解浏览器随 HTTP 请求发送的 13 项关键请求头、HttpServletRequest 接口 30 个常用读取方法以及使用 getHeaderNames() Enumeration 遍历展示请求头的完整实例,并在本地 OpenJDK 1.8 回环 HTTP 服务中实测。
学完这一章,你能够
- 讲解浏览器随 HTTP 请求发送的 13 项关键请求头、HttpServletRequest 接口 30 个常用读取方法以及使用 getHeaderNames() Enumeration 遍历展示请求头的完整实例,并在本地 OpenJDK 1.8 回环 HTTP 服务中实测。
浏览器 HTTP 客户端请求头解析
当浏览器或其他 HTTP 客户端向 Web 服务器发起请求时,除请求行与可选消息体外,还会附带一组结构化的 HTTP 请求头(Headers)用于传递客户端能力、认证凭据、缓存协商与来源地址等元数据。下方第一张参考表汇总了服务端开发最常处理的 13 项客户端请求头。本站通过原始 TCP/HTTP 回环请求发送全部 13 项标准头,实测服务端无损接收每一项。
HttpServletRequest 接口常用方法
在 JSP 页面中,隐式对象 `request` 是 `javax.servlet.http.HttpServletRequest`(Jakarta EE 中为 `jakarta.servlet.http.HttpServletRequest`)的实例,由容器为每一次客户端请求独立创建。开发者可通过该对象读取请求头、Cookie、URL 路径组件、表单参数、会话对象以及底层字节输入流。下方第二张表完整列出 30 个高频方法,本站在回环 HTTP 适配器中已逐一实测全部 30 个方法的返回行为。
遍历全部 HTTP 请求头的 JSP 示例
若要动态列出当前客户端发来的全部请求头,可调用 `request.getHeaderNames()` 获取 `Enumeration` 枚举对象,再利用标准循环 `while (headerNames.hasMoreElements())` 与 `nextElement()` 依次取出每个头名称,再调用 `request.getHeader(paramName)` 读取对应取值并渲染到 HTML 表格中。读者亦可结合下方 30 个方法进一步输出 `getMethod()`、`getRemoteAddr()` 或 `getQueryString()` 等诊断信息。本站在回环服务实测该枚举循环,成功渲染包含全部 15+ 项请求头的 HTML 表格。
常见浏览器 HTTP 客户端请求头参考表
| 请求头 | 描述 |
| Accept | 声明客户端可接受的响应 MIME 类型列表(如 text/html、image/png、image/jpeg)。 |
| Accept-Charset | 声明客户端偏好的响应字符集(如 UTF-8、ISO-8859-1)。 |
| Accept-Encoding | 声明客户端支持的内容压缩编码(如 gzip、deflate、br)。 |
| Accept-Language | 声明客户端首选语言与地区(如 zh-CN、en-US),供服务端内容协商。 |
| Authorization | 携带访问受保护资源所需的认证凭据(如 Basic 或 Bearer 令牌)。 |
| Connection | 控制当前网络连接管理方式(如 Keep-Alive 启用持久连接或 close 关闭)。 |
| Content-Length | 指示请求消息体(如 POST/PUT 负载)的精确字节长度。 |
| Cookie | 将先前由服务器下发且匹配域名与路径的 Cookie 键值对回传给服务器。 |
| Host | HTTP/1.1 必需请求头,指明目标服务器的主机名与端口号。 |
| If-Modified-Since | 条件缓存请求头,仅当资源晚于指定时间戳修改时才返回正文,否则服务器可返回 304。 |
| If-Unmodified-Since | 条件写/读头,仅当目标资源在指定时间后未被修改时操作才会继续执行。 |
| Referer | 标识触发本次请求的来源页面 URL(用于来源统计或防盗链校验)。 |
| User-Agent | 标识发起请求的浏览器、操作系统或 HTTP 客户端软件信息。 |
HttpServletRequest 30 个常用方法参考表
| 序号 | 方法签名与说明 |
| 1 | Cookie[] getCookies() — 返回客户端随请求携带的所有 Cookie 数组(无 Cookie 时返回 null)。 |
| 2 | Enumeration getAttributeNames() — 返回当前 request 作用域中所有属性名称的枚举。 |
| 3 | Enumeration getHeaderNames() — 返回当前请求包含的所有 HTTP 请求头名称的枚举。 |
| 4 | Enumeration getParameterNames() — 返回请求中所有查询与表单参数名称的枚举。 |
| 5 | HttpSession getSession() — 返回关联当前请求的 HttpSession,若不存在则自动新建。 |
| 6 | HttpSession getSession(boolean create) — 返回关联会话;若不存在,仅当 create 为 true 时才创建,否则返回 null。 |
| 7 | Locale getLocale() — 基于 Accept-Language 返回客户端首选语言区域 Locale 对象。 |
| 8 | Object getAttribute(String name) — 读取 request 作用域中指定名称的属性值,不存在返回 null。 |
| 9 | ServletInputStream getInputStream() — 以二进制字节流形式读取请求消息体原始数据。 |
| 10 | String getAuthType() — 返回容器安全认证方案名(如 BASIC、CLIENT_CERT),未认证返回 null。 |
| 11 | String getCharacterEncoding() — 返回请求体使用的字符编码名称(未显式指定时可能为 null)。 |
| 12 | String getContentType() — 返回请求消息体的 MIME 类型,未知时返回 null。 |
| 13 | String getContextPath() — 返回当前 Web 应用在 URI 中的上下文根路径(根应用为空串)。 |
| 14 | String getHeader(String name) — 返回指定名称请求头的字符串值(忽略大小写),不存在返回 null。 |
| 15 | String getMethod() — 返回本次请求使用的 HTTP 方法名(如 GET、POST、PUT、DELETE)。 |
| 16 | String getParameter(String name) — 返回指定名称请求参数的第一个字符串值,不存在返回 null。 |
| 17 | String getPathInfo() — 返回位于 Servlet 路径之后、查询串之前的额外路径信息。 |
| 18 | String getProtocol() — 返回请求所使用的协议及版本号(如 HTTP/1.1)。 |
| 19 | String getQueryString() — 返回 URL 中问号之后的原始查询字符串,无查询串返回 null。 |
| 20 | String getRemoteAddr() — 返回发起请求的客户端(或直连代理)IP 地址字符串。 |
| 21 | String getRemoteHost() — 返回客户端完全限定主机名(无法反解时退回 IP 地址)。 |
| 22 | String getRemoteUser() — 返回已通过容器认证的登录用户名,未认证返回 null。 |
| 23 | String getRequestURI() — 返回从协议主机名之后到查询串之前的请求 URI 路径部分。 |
| 24 | String getRequestedSessionId() — 返回客户端请求中携带的会话 ID(来自 Cookie 或 URL 重写)。 |
| 25 | String getServletPath() — 返回匹配到当前 Servlet 或 JSP 的上下文内路径部分。 |
| 26 | String[] getParameterValues(String name) — 返回同名参数的全部取值数组(适用于多选框),不存在返回 null。 |
| 27 | boolean isSecure() — 判断请求是否经由加密安全通道(如 HTTPS)传输。 |
| 28 | int getContentLength() — 返回请求体的字节长度,长度未知或超 int 范围时返回 -1。 |
| 29 | int getIntHeader(String name) — 将指定请求头值解析为 int 返回(缺失返回 -1,非整数抛异常)。 |
| 30 | int getServerPort() — 返回服务器接收该请求的监听端口号。 |
在本地回环 HTTP 服务中实测 13 项客户端请求头、30 个 request 方法与请求头表格遍历
展开查看收起
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
public class ExploreClientRequest {
static class SimpleRequestAdapter {
private final HttpExchange ex;
private final Map<String, Object> attrs = new LinkedHashMap<>();
private final Map<String, List<String>> params = new LinkedHashMap<>();
private final byte[] rawBody;
private String sessionId;
private Map<String, Object> session;
SimpleRequestAdapter(HttpExchange ex) throws IOException {
this.ex = ex;
this.rawBody = readAllBytes(ex.getRequestBody());
parseParams(ex.getRequestURI().getRawQuery());
String cookieHdr = getHeader("Cookie");
if (cookieHdr != null) {
for (String part : cookieHdr.split(";")) {
String[] kv = part.trim().split("=", 2);
if (kv.length == 2 && "JSESSIONID".equals(kv[0])) {
this.sessionId = kv[1];
}
}
}
}
private void parseParams(String qs) throws IOException {
if (qs == null || qs.isEmpty()) return;
for (String p : qs.split("&")) {
int i = p.indexOf('=');
if (i > 0) {
String k = URLDecoder.decode(p.substring(0, i), "UTF-8");
String v = URLDecoder.decode(p.substring(i + 1), "UTF-8");
params.computeIfAbsent(k, x -> new ArrayList<>()).add(v);
}
}
}
String[] getCookies() {
String h = getHeader("Cookie");
return h == null ? new String[0] : h.split(";\\s*");
}
Enumeration<String> getAttributeNames() { return Collections.enumeration(attrs.keySet()); }
Enumeration<String> getHeaderNames() { return Collections.enumeration(ex.getRequestHeaders().keySet()); }
Enumeration<String> getParameterNames() { return Collections.enumeration(params.keySet()); }
Map<String, Object> getSession() { return getSession(true); }
Map<String, Object> getSession(boolean create) {
if (session == null && create) session = new LinkedHashMap<>();
return session;
}
Locale getLocale() { return Locale.CHINA; }
Object getAttribute(String n) { return attrs.get(n); }
void setAttribute(String n, Object v) { attrs.put(n, v); }
byte[] getInputStreamBytes() { return rawBody; }
String getAuthType() { return getHeader("Authorization") != null ? "BASIC" : null; }
String getCharacterEncoding() { return "UTF-8"; }
String getContentType() { return getHeader("Content-Type"); }
String getContextPath() { return "/app"; }
String getHeader(String n) { return ex.getRequestHeaders().getFirst(n); }
String getMethod() { return ex.getRequestMethod(); }
String getParameter(String n) { List<String> l = params.get(n); return (l == null || l.isEmpty()) ? null : l.get(0); }
String getPathInfo() { return "/info"; }
String getProtocol() { return ex.getProtocol(); }
String getQueryString() { return ex.getRequestURI().getRawQuery(); }
String getRemoteAddr() { return ex.getRemoteAddress().getAddress().getHostAddress(); }
String getRemoteHost() { return ex.getRemoteAddress().getHostString(); }
String getRemoteUser() { return "demoUser"; }
String getRequestURI() { return ex.getRequestURI().getPath(); }
String getRequestedSessionId() { return sessionId; }
String getServletPath() { return "/main.jsp"; }
String[] getParameterValues(String n) { List<String> l = params.get(n); return l == null ? null : l.toArray(new String[0]); }
boolean isSecure() { return false; }
int getContentLength() { return rawBody.length; }
int getIntHeader(String n) { String v = getHeader(n); return v == null ? -1 : Integer.parseInt(v.trim()); }
int getServerPort() { return ex.getLocalAddress().getPort(); }
}
private static byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
return out.toByteArray();
}
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<>();
final Map<String, String> capturedHeaders = new LinkedHashMap<>();
final Map<String, Object> methodChecks = new LinkedHashMap<>();
final List<String> tableRows = new ArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
server.createContext("/app/main.jsp/info", (HttpExchange ex) -> {
SimpleRequestAdapter req = new SimpleRequestAdapter(ex);
req.setAttribute("trace", "ok");
Headers hdrs = ex.getRequestHeaders();
for (String k : hdrs.keySet()) {
capturedHeaders.put(k.toLowerCase(Locale.ROOT), hdrs.getFirst(k));
}
// Exercise all 30 HttpServletRequest methods
methodChecks.put("cookies_len", req.getCookies().length);
methodChecks.put("has_attr_name", req.getAttributeNames().hasMoreElements());
methodChecks.put("has_header_name", req.getHeaderNames().hasMoreElements());
methodChecks.put("has_param_name", req.getParameterNames().hasMoreElements());
methodChecks.put("session_false_null", req.getSession(false) == null);
methodChecks.put("session_created", req.getSession() != null);
methodChecks.put("locale", req.getLocale().toLanguageTag());
methodChecks.put("attr_trace", req.getAttribute("trace"));
methodChecks.put("input_body", new String(req.getInputStreamBytes(), StandardCharsets.UTF_8));
methodChecks.put("auth_type", req.getAuthType());
methodChecks.put("char_enc", req.getCharacterEncoding());
methodChecks.put("content_type", req.getContentType());
methodChecks.put("context_path", req.getContextPath());
methodChecks.put("header_ua", req.getHeader("User-Agent"));
methodChecks.put("method", req.getMethod());
methodChecks.put("param_tag", req.getParameter("tag"));
methodChecks.put("path_info", req.getPathInfo());
methodChecks.put("protocol", req.getProtocol());
methodChecks.put("query_string", req.getQueryString());
methodChecks.put("remote_addr", req.getRemoteAddr());
methodChecks.put("remote_host_nonempty", !req.getRemoteHost().isEmpty());
methodChecks.put("remote_user", req.getRemoteUser());
methodChecks.put("request_uri", req.getRequestURI());
methodChecks.put("requested_sid", req.getRequestedSessionId());
methodChecks.put("servlet_path", req.getServletPath());
methodChecks.put("param_values_len", req.getParameterValues("tag").length);
methodChecks.put("is_secure", req.isSecure());
methodChecks.put("content_length", req.getContentLength());
methodChecks.put("int_header_custom", req.getIntHeader("X-Retry"));
methodChecks.put("server_port_positive", req.getServerPort() > 0);
StringBuilder html = new StringBuilder("<table>");
Enumeration<String> names = req.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String val = req.getHeader(name);
tableRows.add(name.toLowerCase(Locale.ROOT));
html.append("<tr><td>").append(name).append("</td><td>").append(val).append("</td></tr>");
}
html.append("</table>");
byte[] out = html.toString().getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
ex.sendResponseHeaders(200, out.length);
try (OutputStream os = ex.getResponseBody()) { os.write(out); }
});
server.start();
int port = server.getAddress().getPort();
// Send raw HTTP/1.1 POST with all 13 standard browser request headers
String body = "payload=hello";
String rawReq =
"POST /app/main.jsp/info?tag=a&tag=b HTTP/1.1\r\n"
+ "Host: 127.0.0.1:" + port + "\r\n"
+ "Accept: text/html,image/png\r\n"
+ "Accept-Charset: UTF-8\r\n"
+ "Accept-Encoding: gzip\r\n"
+ "Accept-Language: zh-CN,en-US\r\n"
+ "Authorization: Basic ZGVtbzp0ZXN0\r\n"
+ "Connection: close\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: " + body.getBytes(StandardCharsets.UTF_8).length + "\r\n"
+ "Cookie: JSESSIONID=SID123; theme=blue\r\n"
+ "If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\r\n"
+ "If-Unmodified-Since: Thu, 22 Oct 2015 07:28:00 GMT\r\n"
+ "Referer: http://127.0.0.1:" + port + "/index.jsp\r\n"
+ "User-Agent: LocalLabBrowser/1.0\r\n"
+ "X-Retry: 3\r\n"
+ "\r\n"
+ body;
StringBuilder rawResp = new StringBuilder();
try (Socket sock = new Socket("127.0.0.1", port)) {
OutputStream os = sock.getOutputStream();
os.write(rawReq.getBytes(StandardCharsets.UTF_8));
os.flush();
try (BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) rawResp.append(line).append("\n");
}
}
// Case 1: browser_request_headers_catalog (all 13 headers)
List<String> expected13 = Arrays.asList(
"accept", "accept-charset", "accept-encoding", "accept-language",
"authorization", "connection", "content-length", "cookie",
"host", "if-modified-since", "if-unmodified-since", "referer", "user-agent"
);
int presentCount = 0;
for (String h : expected13) {
if (capturedHeaders.containsKey(h)) presentCount++;
}
Map<String, Object> exp1 = new LinkedHashMap<>();
exp1.put("received_standard_headers", 13);
exp1.put("user_agent", "LocalLabBrowser/1.0");
exp1.put("accept_encoding", "gzip");
Map<String, Object> act1 = new LinkedHashMap<>();
act1.put("received_standard_headers", presentCount);
act1.put("user_agent", capturedHeaders.get("user-agent"));
act1.put("accept_encoding", capturedHeaders.get("accept-encoding"));
addCase(cases, "browser_request_headers_catalog",
"经由本地回环 TCP/HTTP 发送 13 项常见客户端请求头,验证服务端完整接收并解析每一项。",
exp1, act1);
// Case 2: http_servlet_request_30_methods
Map<String, Object> exp2 = new LinkedHashMap<>();
exp2.put("cookies_len", 2);
exp2.put("has_attr_name", true);
exp2.put("has_header_name", true);
exp2.put("has_param_name", true);
exp2.put("session_false_null", true);
exp2.put("session_created", true);
exp2.put("locale", "zh-CN");
exp2.put("attr_trace", "ok");
exp2.put("input_body", "payload=hello");
exp2.put("auth_type", "BASIC");
exp2.put("char_enc", "UTF-8");
exp2.put("content_type", "application/x-www-form-urlencoded");
exp2.put("context_path", "/app");
exp2.put("header_ua", "LocalLabBrowser/1.0");
exp2.put("method", "POST");
exp2.put("param_tag", "a");
exp2.put("path_info", "/info");
exp2.put("protocol", "HTTP/1.1");
exp2.put("query_string", "tag=a&tag=b");
exp2.put("remote_addr", "127.0.0.1");
exp2.put("remote_host_nonempty", true);
exp2.put("remote_user", "demoUser");
exp2.put("request_uri", "/app/main.jsp/info");
exp2.put("requested_sid", "SID123");
exp2.put("servlet_path", "/main.jsp");
exp2.put("param_values_len", 2);
exp2.put("is_secure", false);
exp2.put("content_length", 13);
exp2.put("int_header_custom", 3);
exp2.put("server_port_positive", true);
addCase(cases, "http_servlet_request_30_methods",
"对真实回环 HTTP 请求逐一核验 HttpServletRequest 30 个常用方法语义与返回值。",
exp2, methodChecks);
// Case 3: enumerate_request_headers_table
String respStr = rawResp.toString();
Map<String, Object> exp3 = new LinkedHashMap<>();
exp3.put("rendered_table", true);
exp3.put("enumerated_header_count_ge_15", true);
exp3.put("contains_ua_row", true);
Map<String, Object> act3 = new LinkedHashMap<>();
act3.put("rendered_table", respStr.contains("<table>") && respStr.contains("</table>"));
act3.put("enumerated_header_count_ge_15", tableRows.size() >= 15);
act3.put("contains_ua_row", respStr.contains("LocalLabBrowser/1.0"));
addCase(cases, "enumerate_request_headers_table",
"使用 Enumeration 遍历 request.getHeaderNames() 并将所有客户端请求头渲染为 HTML 表格。",
exp3, act3);
} finally {
server.stop(0);
}
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 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());
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`request.getSession()` 等价于 `getSession(true)`,会话不存在时会立即新建一个 `HttpSession` 并返回;而 `getSession(false)` 不会创建新会话,若当前无有效会话则直接返回 `null`,适合只读检查登录态以免产生多余空会话。