【问题标题】:In Spring, how do I bind a list of integers to a RequestParam?在 Spring 中,如何将整数列表绑定到 RequestParam?
【发布时间】:2013-01-14 19:05:48
【问题描述】:

我有来自客户端的参数正在发送,例如

ids[] = 11
ids[] = 12
ids[] = 21

在服务器端,我有一个 Spring 控制器,方法如下:

@RequestMapping("/delete.x")
public @ResponseBody Map<String, Object> delete(HttpServletRequest request, @RequestParam("ids[]") List<Integer> ids) {

当我尝试按如下方式遍历 id 集合时:

for (Integer id : ids) {

我得到一个异常如下:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

Spring 是否将 id 的类型更改为 List?不管我怎么想,我怎样才能避免这个问题,并将 ID 作为整数存储在 List 中?

【问题讨论】:

    标签: spring http-request-parameters


    【解决方案1】:

    您面临的问题是 java 有类型擦除。所以在运行时 List&lt;Integer&gt; 等同于 List&lt;String&gt; 并且 spring 无法知道你想要 Integers 到你的列表中。

    解决方法可能是使用整数数组而不是整数列表。

    @RequestMapping("/delete.x")
    public @ResponseBody Map<String, Object> delete(HttpServletRequest request,
      @RequestParam("ids[]") Integer[] ids) {
    

    【讨论】:

      【解决方案2】:

      对于字符串,我已经这样做了,并且运行正常

      <form action="addArticals">
          <input name="artical[]" type="text"> </input>
          <input name="artical[]" type="text"> </input>
          <input name="artical[]" type="text"> </input>
          <input name="artical[]" type="text"> </input>
          .
          .
          .
          .
          <input name="artical[]" type="text"> </input>
      </form>
      

      在控制器中会是这样的

      @RequestMapping("/addArticals")
      public String articalStore(@RequestParam("artical[]")List<String> articals, Modal modal)
      {
      }
      

      【讨论】:

      • OP 明确指出他希望 Spring 绑定到 Integer 而不是 String。字符串在这里不是问题。
      猜你喜欢
      • 2016-06-30
      • 2011-06-03
      • 2016-10-10
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多