2010-10-18 39 views
2

我试图发送一个Ajax请求,Spring MVC的控制器,并将其映射到相应的Java类:春3.0 MVC阿贾克斯例如

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()) 
    //......  
     } 

它看起来像没有来自服务器的响应。如果我使用招,我看到来自服务器的以下消息:

,因为请求的实体是不被请求方式请求 资源支持的格式 服务器拒绝这个请求 () 。

我在做什么错?

+2

我们需要看看您的spring appcontext的内容 – skaffman 2010-10-18 10:54:43

回答

5

有两个可能的原因:

  • 你忘了<mvc:annotation-driven />。它自动配置使用的HTTP消息转换器@RequestBody/@ResponseBody
  • 您在类路径中没有Jackson JSON Processor。春要求其绑定到application/json@RequestBody
+0

我添加了Jackson JSON处理器。如何现在我有以下异常org.codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段"名字"(类com.doolloop.Person),未标记为可忽略 – 2010-10-18 14:26:57

+0

@danny:如果您的'人'具有相应的财产,也许你需要使用财产风格的大写:'firstName' – axtavt 2010-10-18 14:29:17

+0

你是完全正确的。非常感谢。 – 2010-10-18 14:47:24

0

只是一对夫妇的其他有用的链接...看看这个春天的博客文章:

http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase/

和@ResponseBody作使用的例子:

https://src.springframework.org/svn/spring-samples/mvc-showcase/

还有ResponseEntity:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html

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

哪里,而不是 “Hello World” 的,你可以返回一个编组对象。