gpt4 book ai didi

javascript - ajax post 调用在将数组发送到 Spring Rest Controller 时导致 400(错误请求)

转载 作者:行者123 更新时间:2023-11-30 07:32:29 27 4
gpt4 key购买 nike

我有 OneToMany 映射为

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

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

我创建了一个 FooRestController 来使用 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);
}

我的ajax POST请求是

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
})

此时我收到错误

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

关于保存 foo 的 barArray 的任何建议。

注意

每当我使用 Postman 发送数据时

{

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

插入数据并在数据库中创建一个新的 foo。

最佳答案

就我的方法而言,问题很明显,您应该在 Postman 中发送 barArray 时发送它,所以编写此代码

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],
}]
})

并在休息 Controller 中进行一些更改,以便以这种方式将 fooId 保存在 Bar 实体中

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

尝试一下,希望现在您不会看到 400 错误。

关于javascript - ajax post 调用在将数组发送到 Spring Rest Controller 时导致 400(错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com