Spring 3.0 MVC Ajax example
15,464
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
Author by
danny.lesnik
Java Expert at Tikal Knowledge. Interesting in Spring/Hibernate/NoSQL/Spring MVC and other Java top edge technology. Twitter LinkedIn Facebook
Updated on June 17, 2022Comments
-
danny.lesnik about 2 years
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?
-
danny.lesnik over 13 yearsI added Jackson JSON Processor. how ever now I have the following exception org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "FirstName" (Class com.doolloop.Person), not marked as ignorable
-
axtavt over 13 years@danny: If your
Person
have a corresponding property, perhaps you need to use property-style capitalization:firstName