【问题标题】:Spring using @ModelAttribute object is emptySpring 使用 @ModelAttribute 对象为空
【发布时间】:2018-08-07 10:56:43
【问题描述】:

POST 请求正文 json 值:

{
    "id" : 452312313231,
    "name" : "b2",
    "floor": 5
}

建筑类代码:

@Entity
@Table(name = "building")
public class Building implements Serializable{

    private static final long serialVersionUID = -3009157732242241606L;
    @Id
    @Column(name = "building_ID")
    @NotNull
    @Digits(fraction = 0, integer = 15)
    private long id;

    @Column(name = "NAME")
    @NotNull
    private String name;

    @Column(name = "floor")
    @NotNull
    @Digits(fraction = 0, integer = 2)
    private int floor;
    public Building() {}
    public Building(long id, String name, int floor) {

        this.id = id;
        this.name = name;
        this.floor = floor;
    }

控制器代码:

@RequestMapping(value = "/building", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseBody
    String post(Model model, @Valid @ModelAttribute("Building") Building building, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("Wrong data");
            return "Null values or worng data please check properly Number = " + result.getErrorCount() + " \n Error : "
                    + result.getAllErrors();
        } else {

            buildingRep.save(building);
            return "Succesfull";
        }
    }

我使用 jpa 来保存数据。为了便于验证,我选择了 @ModelAttribute 而不是 @RequestBody。问题是建筑对象总是空的。 我在用 json 对象做任何事情吗?

【问题讨论】:

    标签: json spring modelattribute


    【解决方案1】:

    @ModelAttribute 是一个注解,它将方法参数或方法返回值绑定到命名模型属性,然后将其公开给 Web 视图。至于@RequestBody,绑定到一个Web请求头,会包含DTO。

    因此,您可以使用 @RequestHeader 而不是 @Valid @ModelAttribute("Building"),它应该可以工作。

    【讨论】:

    • 您好 Tejash 感谢您的快速重播。但我想在 ModelAttribute 工作。 RequestHeader 工作正常,但@valid 属性是我想要的
    猜你喜欢
    • 2014-12-20
    • 2017-07-16
    • 2012-12-03
    • 2018-05-20
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2020-05-05
    相关资源
    最近更新 更多