gpt4 book ai didi

java - 从 ajax 发送 POST 方法后出现 404 错误(@ResponseStatus 和 ResponseEntity)

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:07:35 24 4
gpt4 key购买 nike

我正在使用 Spring MVC 并尝试使用 jQuery。我的网页上有这个:

$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
});
});
});

Spring 服务器有这个:

@RequestMapping(value = "ajaxJsonPost", method = RequestMethod.POST)
public void postJson(@RequestBody Entity en) throws IOException {
System.out.println("writing entity: " + en.toString());
}

好的,实体来到服务器。但是浏览器控制台打印 404 not found。我知道我的 POST 请求需要任何响应。在 Internet 上,我找到了建议我返回 ResponseEntity 对象或使用注释 @ResponseStatus 的解决方案。它们都能很好地返回 HttpStatus,但我不知道在哪些情况下应该使用它们。什么是最好的方法?

最佳答案

@Controller
@RequestMapping("/apipath")
public class SomeController {
@RequestMapping(value = "/ajaxJsonPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String postJson(@RequestBody final Entity en) {
System.out.println(en.toString());

//assuming you have a class "EntityService" and
//it has a method postData
//which takes Entity object as parameter and pushes into database.
EntityService.postData(en);

System.out.println("added");
return "success";
}
}

服务器端的实体对象

@JsonAutoDetect
public class Entity {

private String mag;
private String paper;

public String getMag() {
return mag;
}

public void setMag(final String mag) {
this.mag = mag;
}

public String getPaper() {
return paper;
}
public void setPaper(final String paper)
this.paper = paper;
}
}

Ajax

$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "/apipath/ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
success : function(response) {
alert(response);
},
error : function() {
alert('error');
}
});
});
});

至于为什么以及何时使用@ResponseStatus 和@ResponseEntity,@Sotirios Delimanolis 在这里已经给出了一个简短的答案。 When use @ResponseEntity .

它说:

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

关于java - 从 ajax 发送 POST 方法后出现 404 错误(@ResponseStatus 和 ResponseEntity),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923016/

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