在使用angularjs内置的$http的服务时,在js中还是像往常使用jquery的$.ajax的方式在data中放置json对象发送到后台的时候,在spring controller的方法中接收不到js传递过来的参数。
通过查询资料得知,使用$.ajax方法向后台发送请求的时候使用的Content-Type
是application/x-www-form-urlencoded;charset=utf-8
,然而angularjs的$http请求使用的Content-Type
是application/json;charset=utf-8
,因此在controller中使用HttpRequestServlet
中的request.getParam
方法的使用获取不到传递的参数。
有两种方法可以解决这个问题:
- 通过修改$http服务的配置,使它的
Content-Type
是application/x-www-form-urlencoded;charset=utf-8
可以通过$httpProvider.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded;charset=utf-8';
然后编写函数把json参数序列化为urlencoded形式就行
- spring配置
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"/> </bean> </mvc:message-converters> </mvc:annotation-driven>
修改默认的RequestMappingHandlerAdapter
为json对象,然后再controller的参数中直接使用@RequestBody注解就能够把js传递过来的对象转换为JSON对象。