gpt4 book ai didi

java - Spring 3.0 MVC Ajax 示例

转载 作者:行者123 更新时间:2023-11-30 06:37:06 25 4
gpt4 key购买 nike

我正在尝试将 Ajax 请求发送到 Spring MVC Controller 并将其相应地映射到 Java 类:

public class Person  implements Serializable {
private MutableLong Id = new MutableLong();
@NotEmpty
@Size(min = 1, max = 50)
String FirstName=null;
@NotEmpty
@Size(min = 1, max = 50)
String LastName=null;
public Person(){}
public long getId(){
return this.Id.longValue();
}
//getters and setters
}

然后我有发送 AJAX 请求的 JavaScript:

function loadXMLDoc(){
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("POST","/authenticate.dlp", true);
xmlHttp.setRequestHeader('Content-Type', 'application/json');
param = '{\"FirstName\"=\"test\",\"LastName\"=\"test2\"}';
xmlHttp.send(param);
}

然后是 Controller 本身:

@RequestMapping(value="/authenticate.dlp",method = RequestMethod.POST)
@ResponseBody
public String getAjax(@RequestBody Person person){
Set<ConstraintViolation<Person>> failures = validator.validate(person);
if(!failures.isEmpty())
//......
}

看起来服务器没有响应。如果我使用的是 Fiddler,我会看到来自服务器的以下响应:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

我做错了什么?

最佳答案

有两个可能的原因:

  • 你忘了<mvc:annotation-driven /> .它自动配置 HTTP 消息转换器以用于 @RequestBody/@ResponseBody
  • 你没有 Jackson JSON Processor在类路径中。 Spring 要求它绑定(bind) application/json@RequestBody

关于java - Spring 3.0 MVC Ajax 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3958387/

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