Java Spring3.0MVCAJAX示例
我试图向Spring MVC控制器发送一个Ajax请求,并相应地将其映射到Java类:Java Spring3.0MVCAJAX示例,java,ajax,spring,spring-mvc,Java,Ajax,Spring,Spring Mvc,我试图向Spring MVC控制器发送一个Ajax请求,并相应地将其映射到Java类: public class Person implements Serializable { private MutableLong Id = new MutableLong(); @NotEmpty @Size(min = 1, max = 50) String FirstName=null; @NotEmpty @Size(min =
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
}
然后我使用JavaScript发送AJAX请求:
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);
}
然后控制器本身:
@RequestMapping(value="/authenticate.dlp",method = RequestMethod.POST)
@ResponseBody
public String getAjax(@RequestBody Person person){
Set<ConstraintViolation<Person>> failures = validator.validate(person);
if(!failures.isEmpty())
//......
}
@RequestMapping(value=“/authenticate.dlp”,method=RequestMethod.POST)
@应答器
公共字符串getAjax(@RequestBody-Person){
设置失败=验证器。验证(人);
如果(!failures.isEmpty())
//......
}
看起来服务器没有响应。如果我正在使用Fiddler,我会看到来自服务器的以下响应:
服务器拒绝了这个请求
因为请求实体位于
请求的文件不支持该格式
请求的方法()的资源
我做错了什么 可能有两个原因:
- 你忘记了
。它自动配置HTTP消息转换器,以便与
/@RequestBody
@ResponseBody
- 在类路径中没有。Spring要求它将
绑定到应用程序/json
@RequestBody
@RequestMapping(“/ajax/helloworld”)
公共响应helloworld(){
HttpHeaders=新的HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
返回新的ResponseEntity(“helloworld”,标题,HttpStatus.OK);
}
您可以在何处而不是“Hello World”返回编组对象。这并不是您问题的答案,但您以前看过DWR吗?它使JS到JavaRPC变得超级简单 我们需要查看spring appcontextI添加的Jackson JSON处理器的内容。但是现在我有以下异常org.codehaus.jackson.map.exc.UnrecognizedPropertyException:未识别字段“FirstName”(Class com.dooloop.Person),未标记为ignorable@danny:如果您的
Person
具有相应的属性,则可能需要使用属性样式大小写:firstName
@RequestMapping("/ajax/helloworld")
public ResponseEntity<String> helloworld() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>("Hello World", headers, HttpStatus.OK);
}