天天看點

SpringMVC對多個同名name參數解析處理

簡潔來說,就是form表單有多個input(checkbox,hidden),name同名,背景是如何接收的。

form表單

<form action="testName.do" method="POST" >
        input1: <input type="text" name="userName"/>
        input2: <input type="text" name="userName"/>
        <input type="submit" value="Submit"/>
</form>      

背景使用String接收

SpringMVC對多個同名name參數解析處理

如圖所示,使用string接收,springmvc會自動将兩個name參數值用英文逗号​

​“,”​

​隔開,拼成字元串指派給參數userName。

背景使用​

​String[]​

SpringMVC對多個同名name參數解析處理

如圖所示,背景使用字元串數組接收,兩個name對應參數值自動封裝為字元串數組。

效果同下:

String[] parameterValues = request.getParameterValues("userName");      

後頭使用List接收

@RequestMapping("testName")
public void testName(HttpServletRequest request, HttpServletResponse response, @RequestParam List userName){
    System.out.println(userName);
}      

列印結果如下:

[123, 456]      

如果不使用​

​@RequestParam​

​或其他注解:

  • 如果定義的是List這種未指定具體類型,則會抛出​

    ​java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection parameter type​

    ​;
  • 如果定義​

    ​List<String>​

    ​​,則會抛出​

    ​java.lang.IllegalStateException: No primary or default constructor found for interface java.util.List​

    ​;
  • 如果定義了​

    ​ArrayList<String>​

    ​,則這裡userName為空。

也就是說SpringMVC内置了轉換,可以從一個英文逗号分隔的字元串轉換為數組、字元串數組或類型轉換系統已知的其他類型。例如一個方法參數​

​@RequestHeader("Accept")​

​​可以是​

​String​

​​類型,也可以是​

​String[] or List<String>​