send json to server spring 3.x
i want to send json to server using Spring 3.x, i use annotation @RequestBody, but my controller don't called.
Please, send me a complete example, if any, I'm trying to use example in http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ but it doesn't work. Here is a javascript code
function sendAjax() {
var person = new Object();
person.firstname = "Firsname";
person.lastname = "Lastname";
jQuery.ajax({
url: "person",
type: 'POST',
dataType: 'json',
data: person,
contentType: 'application/json',
success: function(data) {
alert(data.firstname + " " + data.lastname);
}
});}
And my controller is
@Controller public class AjaxController {
@RequestMapping(value="person", method = RequestMethod.POST)
public @ResponseBody Person getRequest(@RequestBody Person person) {
System.out.println(person.getFirstname() + " " + person.getLastname());
return new Person("Return", "Body");
}}
my xml file
<mvc:annotation-driven />
<context:component-scan base-package="com.synisys.spring.test.controllers" />
<context:annotation-config/>
<mvc:resources mapping="/js/**" location="/js/"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
开发者_Python百科 <list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
Please make sure you have
<context:annotation-config/>
and also
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
In your spring xml conf file.
in your ajax call add
var dat = JSON.stringify({
"firstname " : firstname ,
"lastname ": lastname
});
jQuery.ajax({
url: "person",
type: 'POST',
dataType: 'json',
data: person,
contentType: 'application/json',
success: function(data) {
alert(data.firstname + " " + data.lastname);
}
});
and make sure you add related dependency (if you are using maven Spring mvc)
精彩评论