JSP 客户端请求

request 对象读参数、头、Cookie,以及 EL 里的 param 系列。

Beginner
Key PointsJSP 里读请求既可以用 request.getParameter,也可以用 EL 的 ${param.x},后者更简洁且自动处理空值。

两种读法

JSP
<%-- 脚本写法 --%>
<p>姓名:<%= request.getParameter("name") %></p>

<%-- EL 写法:null 时输出空串,不会显示 null --%>
<p>姓名:${param.name}</p>

<%-- 多值参数(复选框) --%>
<p>爱好:${paramValues.hobby[0]}、${paramValues.hobby[1]}</p>
ELEquivalent
${param.x}request.getParameter("x")
${paramValues.x}request.getParameterValues("x")
${header.x}request.getHeader("x")
${headerValues.x}request.getHeaders("x")
${cookie.x.value}遍历 request.getCookies()
${pageContext.request.method}request.getMethod()

表单处理

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    boolean submitted = name != null;
%>
<!DOCTYPE html>
<html><body>
<% if (!submitted) { %>
  <form method="post">
    姓名:<input name="name"><button>提交</button>
  </form>
<% } else { %>
  <p>收到:${fn:escapeXml(param.name)}</p>
<% } %>
</body></html>

One page both renders the form and handles the submit, deciding on whether the parameter is null. It is the simplest approach, but refreshing resubmits; real projects redirect after POST.

读请求头

JSP
<p>浏览器:${header['User-Agent']}</p>
<p>来源页:${header.referer}</p>
<p>语言:${header['Accept-Language']}</p>
<p>方法:${pageContext.request.method}</p>
<p>路径:${pageContext.request.requestURI}</p>

A header name containing a hyphen cannot use ${header.Accept-Language} — EL reads - as minus. Write ${header['Accept-Language']} instead.

安全提醒

JSP
<%-- 危险:参数原样输出,可注入脚本 --%>
<p>${param.comment}</p>

<%-- 安全:转义后再输出 --%>
<p><c:out value="${param.comment}"/></p>
<p>${fn:escapeXml(param.comment)}</p>
EL in JSP 2.x does not escape output; ${param.x} injected into HTML is XSS. Use <c:out> or fn:escapeXml — pick one and never skip it.

Friends & Partners