Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC @RequestParam a list of objects

I want to create a page where a person sees a list of users and there are check boxes next to each of them that the person can click to have them deleted.

In my MVC that consumes a REST API, I want to send a List of User objects to the REST API.

Can the @RequestParam annotation support that?

For example:

@RequestMapping(method = RequestMethod.DELETE, value = "/delete")
    public @ResponseBody Integer delete(
            @RequestParam("users") List<Users> list) {
        Integer deleteCount = 0;
        for (User u : list) {
            if (u != null) {
                repo.delete(u);
                ++deleteCount;
            }
        }
        return deleteCount;
    }

In the MVC client, the url would be:

List list = new ArrayList<User>();
....
String url = "http://restapi/delete?users=" + list;
like image 997
Kingamere Avatar asked Oct 26 '15 19:10

Kingamere


People also ask

What is @RequestParam annotation in Spring MVC?

@RequestParam is a Spring annotation used to bind a web request parameter to a method parameter. It has the following optional elements: defaultValue - used as a fallback when the request parameter is not provided or has an empty value. name - name of the request parameter to bind to.

What is the use of @RequestParam in Spring MVC?

In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.

What is difference between @PathVariable and @RequestParam in Spring?

Difference between @PathVariable and @RequestParam in Spring 1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.


1 Answers

Request parameters are a Multimap of String to String. You cannot pass a complex object as request param.

But if you just pass the username that should work - see how to capture multiple parameters using @RequestParam using spring mvc?

@RequestParam("users") List<String> list

But I think it would be better to just use the request body to pass information.

like image 69
Mathias Dpunkt Avatar answered Sep 25 '22 07:09

Mathias Dpunkt