2010-10-18 42 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」 的,你可以返回一個編組對象。