2

POST request body json value :

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

code of Building class :

@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;
    }

Code of controller :

@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";
        }
    }

im using jpa to save data . and i chosed @ModelAttribute over @RequestBody for easy validation . Problem is building object is always empty. im i doing anything worng with json object ?

Masood
  • 909
  • 7
  • 11

1 Answers1

0

The @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view. As for @RequestBody, is bound to a web request header and will contain DTO.

So instead of @Valid @ModelAttribute("Building"), you can use @RequestHeader and it should work.

Tejash L
  • 9
  • 2
  • 5
  • Hello Tejash thank you for your quick replay . But i want to work in ModelAttribute . RequestHeader works fine but @valid property is what i want – Masood Feb 28 '18 at 08:44