在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在 DispatcherServlet 中就会将请求参数赋值给相应的形参。

    示例:**获取key与value一对多单的参数,hobby对多个参数
    HTML:**

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. </head>
    7. <body>
    8. <h1>首页</h1>
    9. <form method="get" th:action="@{/testParame}">
    10. 用户名:<input type="text" name="username"><br/>
    11. 密码:<input type="password" name="password"><br/>
    12. 爱好:<input type="checkbox" name="hobby" value="Java">Java
    13. <input type="checkbox" name="hobby" value="C++">C++
    14. <input type="checkbox" name="hobby" value="C"><br/>C
    15. <input type="submit" value="提交">
    16. </form>
    17. </body>
    18. </html>

    Controller:
    可以使用 String hobby 获取
    也可以 String[] hobby 获取

    1. package com.way.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import javax.servlet.http.HttpServletRequest;
    6. @Controller
    7. public class MyController {
    8. @RequestMapping(value = "/testParame")
    9. public String testParm(String username, Integer password,String hobby) {//String[] hobby
    10. System.out.println("username:" + username + ";" +
    11. "password:" + password + ";" +
    12. "hobby:" + hobby);
    13. return "target";
    14. }
    15. 或者: 此为标记两种方法,实际两个方法testParm不能同时存在。
    16. @RequestMapping(value = "/testParame")
    17. public String testParm(String username, Integer password,String[] hobby) {
    18. System.out.println("username:" + username + ";" +
    19. "password:" + password + ";" +
    20. "hobby:" + Arrays.toString(hobby));
    21. return "target";
    22. }
    23. }

    浏览器结果:
    image.png
    idea结果:

    username:王子尧;password:941941;hobby:Java,C++,C

    注:

    • 若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串
    • 数组或者字符串类型的形参接收此请求参数
    • 若使用字符串数组类型的形参,此参数的数组中包含了每一个数据
    • 若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果