首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Servlet 獲取 HTML 表單多值參數:Select 多選、Radio、Checkbox、同名 Input 完整指南

     編輯:Java 相關知識

核心 API:request.getParameterValues(String name)

返回 String[],包含同名參數的所有值;若無該參數返回 null;若單值返回長度為 1 的數組。適用於所有多值場景:<select multiple>、同名 checkbox、同名 input、同名 radio (罕見) 等。

前端表單構建示例

1. Select 多選

<select name="skills" multiple size="5">
    <option value="java">Java</option>
    <option value="python">Python</option>
    <option value="go">Go</option>
    <option value="rust">Rust</option>
    <option value="js">JavaScript</option>
</select>

用戶按住 Ctrl/Cmd 點擊可多選,提交時瀏覽器發送多個 skills=java&skills=go 參數。

2. Checkbox 組 (同名)

<label><input type="checkbox" name="colors" value="red"> 紅</label>
<label><input type="checkbox" name="colors" value="green"> 綠</label>
<label><input type="checkbox" name="colors" value="blue"> 藍</label>

勾選紅、藍 → 提交 colors=red&colors=blue。未勾選的 checkbox 不發送任何參數。

3. Radio 單選 (同名)

<label><input type="radio" name="gender" value="male"> 男</label>
<label><input type="radio" name="gender" value="female"> 女</label>
<label><input type="radio" name="gender" value="other"> 其他</label>

同名 radio 互斥,僅提交一個值,但 getParameterValues 仍返回長度 1 的數組,代碼統一處理。

4. 同名 Input 文本框 (動態添加)

<div id="phones">
    <input type="text" name="phone" placeholder="手機號">
</div>
<button type="button" onclick="addPhone()">+ 添加號碼</button>

<script>
function addPhone() {
    const div = document.createElement('div');
    div.innerHTML = '<input type="text" name="phone" placeholder="手機號">';
    document.getElementById('phones').appendChild(div);
}
</script>

用戶填寫 3 個號碼 → 提交 3 個 phone=... 參數。

Servlet 統一處理代碼

@WebServlet("/form-handler")
public class MultiValueServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8"); // 必須在讀取參數前設置

        // 1. Select 多選
        String[] skills = req.getParameterValues("skills");
        printArray("技能", skills);

        // 2. Checkbox 組
        String[] colors = req.getParameterValues("colors");
        printArray("顏色", colors);

        // 3. Radio 單選
        String[] gender = req.getParameterValues("gender");
        printArray("性別", gender);

        // 4. 同名 Input
        String[] phones = req.getParameterValues("phone");
        printArray("手機號", phones);

        // 5. 單值參數 (兼容寫法)
        String username = req.getParameter("username"); // 等同 getParameterValues("username")[0]
        System.out.println("用戶名: " + username);

        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("<h3>接收成功,查看控制台輸出</h3>");
    }

    private void printArray(String label, String[] arr) {
        if (arr == null || arr.length == 0) {
            System.out.println(label + ": (未提交或為空)");
            return;
        }
        System.out.print(label + ": ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < arr.length - 1) System.out.print(", ");
        }
        System.out.println();
    }
}

Spring MVC / Spring Boot 控制器寫法

數組綁定

@PostMapping("/api/form")
public ResponseEntity handleForm(
        @RequestParam(value = "skills", required = false) String[] skills,
        @RequestParam(value = "colors", required = false) String[] colors,
        @RequestParam(value = "gender", required = false) String[] gender,
        @RequestParam(value = "phone", required = false) String[] phones) {

    log.info("skills: {}", Arrays.toString(skills));
    log.info("colors: {}", Arrays.toString(colors));
    log.info("gender: {}", Arrays.toString(gender));
    log.info("phones: {}", Arrays.toString(phones));
    return ResponseEntity.ok("OK");
}

List 綁定 (自動轉換)

@PostMapping("/api/form-list")
public ResponseEntity handleFormList(
        @RequestParam(value = "skills", required = false) List skills) {
    // Spring 自動將多值參數綁定到 List
    log.info("skills list: {}", skills);
    return ResponseEntity.ok("OK");
}

常見坑點與避坑指南

問題現象原因解決
中文亂碼接收到的值為亂碼請求編碼未設置 / Tomcat 版本差異Filter/FilterRegistrationBean 設置 request.setCharacterEncoding("UTF-8");Tomcat 8+ URIEncoding="UTF-8"
未勾選 Checkbox 為 nullgetParameterValues("colors") 返回 null瀏覽器不發送未勾選 checkbox業務邏輯判斷 arr == null 視為空集合
單值參數用 getParameterValues返回長度 1 數組API 設計如此正常,arr[0] 即單值
文件上傳 multipart/form-datagetParameterValues 返回 null請求體非 application/x-www-form-urlencoded用 request.getPart() / @RequestPart MultipartFile / Commons FileUpload
參數名大小寫不匹配獲取不到值HTML name 屬性區分大小寫前後端統一命名規範 (推薦 camelCase 或 kebab-case)

最佳實踐清單

  1. 統一用 getParameterValues 處理所有參數,單值取 [0],代碼更健壯。
  2. 前端 name 屬性語義化:技能用 skills、顏色用 colors,避免 item1、item2 無意義命名。
  3. 必填驗證前端 + 後端雙重:HTML required、JS 校驗、後端 @NotNull/@Size(min=1)。
  4. 編碼過濾器全局攔截:CharacterEncodingFilter (Spring) 或自定義 Filter 設置 UTF-8。
  5. 文件上傳單獨處理:不要混用 getParameterValues 獲取文件域,用 MultipartFile。

總結

ServletRequest.getParameterValues(String name) 是處理 HTML 表單多值參數的統一入口。無論是 select multiple、同名 checkbox/input/radio,瀏覽器均以重複參數名形式提交,Servlet 容器聚合為字符串數組。掌握此 API、理解瀏覽器提交機制、做好編碼與空值處理,即可輕松應對各類複雜表單場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved