In Spring, how do I bind a list of integers to a RequestParam?
Asked Answered
E

2

10

I have parameters from the client that are being sent such as

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

On the server side, I have a Spring controller with the following method:

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

When I try to iterate over the collection of ids as follows:

for (Integer id : ids) {

I get an exception as follows:

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

Is Spring changing the type of ids to List<String>? No matter I suppose, how can I avoid this issue and have the ids stored as Integers inside of a List?

Evonneevonymus answered 14/1, 2013 at 19:5 Comment(0)
I
17

The problem you are facing is that java has type erasure. So at runtime a List<Integer> is equivalent than a List<String> and spring has no way of knowing you want Integers into your list.

A work around might be using a integer array instead of a List of integers.

@RequestMapping("/delete.x")
public @ResponseBody Map<String, Object> delete(HttpServletRequest request,
  @RequestParam("ids[]") Integer[] ids) {
Irruption answered 14/1, 2013 at 19:23 Comment(0)
C
1

For string I have done like this and this running properly

<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>

and in controller it will be like this

@RequestMapping("/addArticals")
public String articalStore(@RequestParam("artical[]")List<String> articals, Modal modal)
{
}
Clotho answered 22/8, 2015 at 4:43 Comment(1)
The OP clearly states that he wants Spring to bind to Integer and not String. String is not an issue here.Bushman

© 2022 - 2024 — McMap. All rights reserved.