JSP 表单处理

GET 与 POST 表单、参数读取、复选框与下拉框、中文编码。

Beginner
Key Points表单字段名就是参数名;复选框多值用 paramValues,单选下拉只传一个值。

GET 表单

JSP
<form action="search.jsp" method="get">
  关键词:<input name="q">
  <button>搜索</button>
</form>

GET appends parameters to the URL: search.jsp?q=java. Bookmarkable, shareable, crawlable, but length-limited and visible — never for passwords.

POST 表单

JSP
<form action="save.jsp" method="post">
  姓名:<input name="name"><br>
  性别:<input type="radio" name="sex" value="m" checked>男
        <input type="radio" name="sex" value="f">女<br>
  爱好:<input type="checkbox" name="hobby" value="read">阅读
        <input type="checkbox" name="hobby" value="run">跑步<br>
  城市:<select name="city">
          <option value="bj">北京</option>
          <option value="sh">上海</option>
        </select><br>
  <button>提交</button>
</form>

接收参数

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String sex  = request.getParameter("sex");
    String city = request.getParameter("city");
    String[] hobbies = request.getParameterValues("hobby");
%>
<p>姓名:<%= name %></p>
<p>性别:<%= "m".equals(sex) ? "男" : "女" %></p>
<p>城市:<%= city %></p>
<p>爱好:<%= hobbies == null ? "未选择" : String.join("、", hobbies) %></p>
Output
姓名:张三
性别:男
城市:北京
爱好:阅读、跑步

EL 写法

JSP
<p>姓名:${param.name}</p>
<p>城市:${param.city}</p>
<p>爱好:${paramValues.hobby[0]}、${paramValues.hobby[1]}</p>

EL prints an empty string instead of null, so no ugly "null" on the page. Array index access throws when out of range, though — iterate with <c:forEach> or check the length first.

回填表单

JSP
<input name="name" value="<c:out value='${param.name}'/>">
<select name="city">
  <option value="bj" ${param.city == 'bj' ? 'selected' : ''}>北京</option>
  <option value="sh" ${param.city == 'sh' ? 'selected' : ''}>上海</option>
</select>
<input type="checkbox" name="hobby" value="read"
       ${fn:contains(fn:join(paramValues.hobby, ','), 'read') ? 'checked' : ''}>阅读

After a validation failure, re-populate what the user typed or they must redo the whole form. This is the most overlooked detail in form UX and one users feel immediately.

request.setCharacterEncoding("UTF-8") must come before the first parameter read. Once parameters are read the encoding is fixed and later calls do nothing — which looks exactly like "all Chinese input is garbled".

Friends & Partners