Spring MVC @RequestParam a list of objects

强颜欢笑 提交于 2019-12-23 20:07:03

问题


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;

回答1:


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.




回答2:


Though this question has been answered and the answer has been accepted, I found that using @RequestBody instead of @RequestParam does exactly what you want, plus it's very easy.

You'd end up with @RequestBody List<Integer> list. You can call your web service with an HTTP request (POST will definitely work, but DELETE should work too) with request body: [id1, id2, ...]. If it doesn't work out of the box like that, try adding consumes = MediaType.APPLICATION_JSON_VALUE) to the @RequestMapping.




回答3:


Spring mvc can support List<Object>, Set<Object> and Map<Object> param, but without @RequestParam.

Take List<Object> as example, if your object is User.java, and it like this:

public class User {
    private String name;
    private int age;

    // getter and setter
}

And you want pass a param of List<User>, you can use url like this

http://127.0.0.1:8080/list?users[0].name=Alice&users[0].age=26&users[1].name=Bob&users[1].age=16

Remember to encode the url, the url after encoded is like this:

http://127.0.0.1:8080/list?users%5B0%5D.name=Alice&users%5B0%5D.age=26&users%5B1%5D.name=Bob&users%5B1%5D.age=16

Example of List<Object>, Set<Object> and Map<Object> is displayed in my github.



来源:https://stackoverflow.com/questions/33354534/spring-mvc-requestparam-a-list-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!