JSP 中获取表单数据
JSP 中获取表单数据的核心是通过request隐式对象(HttpServletRequest),结合 EL/JavaBeans 等方式,支持GET/POST 提交的表单参数读取,具体有以下 3 种常用方式:
前提:表单示例(POST 提交)
1 2 3 4 5 6 7
| <form action="submit.jsp" method="post"> 用户名:<input type="text" name="username"/><br> 年龄:<input type="number" name="age"/><br> 爱好:<input type="checkbox" name="hobby" value="读书"/>读书 <input type="checkbox" name="hobby" value="运动"/>运动<br> <input type="submit" value="提交"/> </form>
|
方式 1:通过 request 隐式对象直接获取(最基础)
核心方法:
String getParameter(String name):获取单个值的参数(如用户名、年龄);
String[] getParameterValues(String name):获取多值参数(如复选框、下拉多选);
Map<String, String[]> getParameterMap():获取所有参数的键值对集合。
示例(submit.jsp):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <%@ page contentType="text/html;charset=UTF-8" %> <% request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); String ageStr = request.getParameter("age"); int age = ageStr != null ? Integer.parseInt(ageStr) : 0; String[] hobbies = request.getParameterValues("hobby"); out.print("用户名:" + username + "<br>"); out.print("年龄:" + age + "<br>"); if (hobbies != null) { out.print("爱好:"); for (String h : hobbies) { out.print(h + " "); } } %>
|
方式 2:通过 EL 表达式获取(简化版)
EL 提供param(单个参数)、paramValues(多值参数)隐式对象,无需写 Java 脚本:
1 2 3 4 5 6 7 8 9 10 11
| <%@ page contentType="text/html;charset=UTF-8" %> <% request.setCharacterEncoding("UTF-8"); %> <!-- 单个参数 --> 用户名:${param.username}<br> 年龄:${param.age}<br>
<!-- 多值参数(需结合JSTL遍历)--> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 爱好:<c:forEach items="${paramValues.hobby}" var="h"> ${h} </c:forEach>
|
方式 3:通过 JavaBeans 自动绑定(高效)
利用<jsp:setProperty>将表单参数直接绑定到 JavaBean 的属性(属性名需与表单 name 一致),无需手动调用getParameter:
1 2 3 4 5 6 7 8 9 10 11 12
| <%@ page contentType="text/html;charset=UTF-8" %> <% request.setCharacterEncoding("UTF-8"); %>
<%-- 1. 创建User实例 --%> <jsp:useBean id="user" class="com.example.User" scope="page"/>
<%-- 2. 自动绑定所有表单参数(属性名与表单name一致)--%> <jsp:setProperty name="user" property="*"/>
<%-- 3. 输出(或用EL)--%> 用户名:<jsp:getProperty name="user" property="username"/><br> 年龄:${user.age}<br>
|
关键注意事项:
中文乱码处理
:
- POST 提交:在获取参数前执行
request.setCharacterEncoding("UTF-8");
- GET 提交:需修改 Tomcat 的
conf/server.xml,在连接器中添加URIEncoding="UTF-8"(如<Connector port="8080" URIEncoding="UTF-8"/>);
空值处理:获取参数后需判断是否为null,避免空指针 / 类型转换异常;
多值参数:复选框、下拉多选需用getParameterValues或paramValues,不能用getParameter(仅返回第一个值)。