最近在做自己的网站,有一个模块是点赞,为了减小不必要的数据传递,考虑用ajax+json与后台(spring mvc)交互实现。
run的时候,后台controller能够接收到前台传来的数据,也能够写入mysql中,但是前台不能接收到返回信息,eclipse抛出出现了如下异常:
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.HashMap.
意思很明显,后台返回的数据与前台接收的不匹配,缺少一个能够转换格式的converter.
首先检查了代码,没有问题,不存在书写错误等低级问题。
然后查了好多资料后,发现可能是springmvc_servlet.xml存在问题(这是个人的命名,其他人可能是applicationContext.xml,主要是配置spring的)。
经修改如下:
springmvc_servlet.xml的关键部分:
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--json转换器-->
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="plain"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="*"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="json"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>
前台ajax+json关键部分:
<script type="text/javascript">
function GearUp(value){
$.ajax({
type:"GET",
contentType:"application/json",
dataType:"json",
url:"/leyuan/reply/......",
data:{"replyid":value},
async:true,
error:function(data){
alert("Failed! "+data);
},
success:function(data){
//alert("Success! "+data.replylike);
//document.getElementById()
document.getElementById("repeat_reply_"+value).innerHTML=data.replylike+" people like this reply !";
}
});
}
</script>
后台controller关键部分:
@RequestMapping("/reply/......")
@ResponseBody
public Map<String,Object> GearUp(HttpServletRequest httpServletRequest) throws Exception{
......
Map<String,Object> map=new HashMap<String, Object>();
map.put("replylike", reply.getReplygearup().toString());
System.out.println(reply.getReplygearup());
return map;