RequestBody 官方指南:
a method parameter should be bound to the value of the HTTP request body(方法参数名要与请求体的json数据的参数名对应)
You convert the request body to the method argument by using an HttpMessageConverter(使用HttpMessageConverter转换器将请求体映射成方法参数)
HttpMessageConverter 转换器配置
- applicationContext.xml中配置jsonHttpMessageConverter转换器
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
ajax、java 应用实例
- js代码
var jsonObj = {"openid":"xxx","username":"Ed sheeran","password":"123"};
/*
Jquery默认Content-Type为application/x-www-form-urlencoded类型
*/
$.ajax({
type: 'POST',
url: "/login",
dataType: "json",
data: JSON.stringify(jsonObj),
contentType : "application/json",
success: function(data) {
console.log(data)
},
error: function() {
console.log("fucking error")
}
});
- Controller 代码
@Controller
public class LoginController {
@PostMapping("/login")
public void login(@RequestBody Form form){
System.err.println(form);
}
}