Spring 3.0 MVC Ajax示例

I'm trying to send an Ajax request to a Spring MVC controller and map it to a Java class accordingly:

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
} 

then I have JavaScript which sends the AJAX request:

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

and then the controller itself:

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

It looks like no response from the server. If I'm using Fiddler, I see the following response from the server:

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

What am I doing wrong?

There are two possible reasons:

  • You forget <mvc:annotation-driven />. It automatically configures HTTP message converters for use with @RequestBody/@ResponseBody
  • You don't have Jackson JSON Processor in the classpath. Spring requires it to bind application/json to @RequestBody

Just a couple of other helpful links...check out this Spring blog post:

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

And the examples which make use of @ResponseBody:

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

There's also 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);
}

Where instead of "Hello World" you could return a marshalled object.

This is not exactly an answer to your question, but have you looked at DWR before? It makes JS to Java RPC super-easy. http://directwebremoting.org/dwr/index.html