简体   繁体   中英

ajax post call causes 400 (Bad Request) on sending array to spring rest controller

I have OneToMany mapping as

@Entity
public class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long fooId;
    private String fooName;     

    @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
    private Set<Bar> bars = new HashSet<Bar>();

    // getters and setters go here
}

and

@Entity
public class Bar implements Serializable {     
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long barId;
    private String barTitle;
    private static final long serialVersionUID = 1L;
    @ManyToOne
    @JoinColumn(name = "fooId")
    private Foo foo;
    // getters and setters go here
}

I've created a FooRestController to save data using ajax

@RequestMapping(value = "/foo/", headers="Accept=*/*", consumes="application/json", method = RequestMethod.POST)
    public ResponseEntity<Void> create(@RequestBody Foo foo) {           
        fooService.saveFoo(foo);
        Set<Bar> bars = foo.getBars();      

        for (Bar bar : bars) {
            barService.savebar(bar);            
        }       

        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

my ajax POST request is

var barArray = [];
bar[0] = "Bar1";
bar[1] = "Bar2";
$.ajax({
    contentType : 'application/json',
    crossDomain: true,
    type: 'POST',
    url: '/foo/',
    dataType : 'json',
    data : JSON.stringify({        
        'fooName' : 'A',
        'bars' : barArray // this line here causes error 
})

at this point I'm getting error as

POST http://localhost:8080/name/foo/ 400 (Bad Request)

any suggestions for saving barArray of foo.

Note

when ever I send data using Postman as

{

    "fooName": "A",       
   "bars" : [
         {
            "barTitle" : "a"                
         }           
       ]
}

data is inserted and a new foo is created in db.

As for as my approach is concerned the problem is clear that you should send barArray as you are sending it in Postman so write this code

var barArray = [];
bar[0] = "Bar1";
bar[1] = "Bar2";
$.ajax({
    contentType : 'application/json',
    crossDomain: true,
    type: 'POST',
    url: '/foo/',
    dataType : 'json',
    data : JSON.stringify({        
        'fooName' : 'A',
        'bars' : [{
                 "barTitle" : bar[0], 
               },{
                 "barTitle" : bar[1], 
               }]
})

and make a bit change in rest controller for saving fooId in Bar entity in this way

@RequestMapping(value = "/foo/", headers="Accept=*/*", consumes="application/json", method = RequestMethod.POST)
    public ResponseEntity<Void> create(@RequestBody Foo foo) {           
        fooService.saveFoo(foo);
        Set<Bar> bars = foo.getBars();      

        for (Bar bar : bars) {
            bar.setFoo(foo); // this foo object comes from method arg @RequestBody Foo foo above
            barService.savebar(bar);            
        }       

        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

try it out and hope now you don't see 400 error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM