Spring Boot Controller端点和ModelAttribute深度访问

时间:2017-07-29 20:15:55

标签: spring spring-boot binding controller modelattribute

我想知道如何在GET请求中访问深集合类属性。我的端点通过@ModelAttribute注释映射我的查询字符串:

鉴于:

public class MyEntity
{
    Set<Item> items;
    Integer status;
    // getters setters
}

public class Item
{
    String name;
    // getters setters
}

我的GET请求:localhost / entities /?status = 0&amp; items [0] .name = Garry

产生波纹管行为?

@RequestMapping(path = "/entities", method = RequestMethod.GET)
public List<MyEntity> findBy(@ModelAttribute MyEntity entity) {
     // entity.getItems() is empty and an error is thrown: "Property referenced in indexed property path 'items[0]' is neither an array nor a List nor a Map."
}

我的“项目”应该是数组,列表还是地图?如果是这样,还有其他选择继续使用Set?

1 个答案:

答案 0 :(得分:0)

看起来Set<Item>存在一些问题。

如果您想为items集合使用Set,则必须对其进行初始化并添加一些项目:

e.g。像这样:

public class MyEntity {
    private Integer status;
    private Set<Item> items;

    public MyEntity() {
        this.status = 0;
        this.items = new HashSet<>();
        this.items.add(new Item());
        this.items.add(new Item());
    }
//getters setters
}

但是您将只能设置这两项的值:

这将有效:http://localhost:8081/map?status=1&items[0].name=asd&items[1].name=aaa

这不起作用:http://localhost:8081/map?status=1&items[0].name=asd&items[1].name=aaa&items[2].name=aaa

它会说:Invalid property 'items[2]' of bean class MyEntity.

但是,如果切换到列表:

public class MyEntity {
    private Integer status;
    private List<Item> items;
}

两个网址都无需初始化任何内容以及各种项目。

请注意,我没有使用@ModelAttribute,只是将该类设置为参数

@GetMapping("map")//GetMapping is just a shortcut for RequestMapping
public MyEntity map(MyEntity myEntity) {
    return myEntity;
}

<强> Offtopic

在Get请求中映射复杂对象听起来像是代码味道给我。 通常,Get方法用于获取/读取数据,url参数用于指定应该用于过滤必须读取的数据的值。

如果要插入或更新某些数据,请使用POST,PATCH或PUT,并将要插入/更新的复杂对象作为JSON放入请求体中(您可以使用{{1}将其映射到Spring Controller中})。