您的位置:首页 > 编程语言 > Java开发

Spring mvc使用注解@ResponseBody Ajax请求返回json报406错误

2016-09-17 20:45 706 查看
之前做的项目依赖jar包jackson-core,jackson--mapper,xml配置<mvc:annotation-driven>就可以轻松使用ResponseBody返回json数据到前台页面。

现在新接手的项目在传json数据时遇到一个很棘手的问题,这个项目用的包是jackson-annotations,jackson-databind,jackson-mapper,前台页面获取数据时报406错误。jar包换回我原来的也不行。

还有网上的各种方法也试过

包括@RequestMapping设置produces = {"application/json;charset=UTF-8"},

和配置

<span style="white-space:pre"> </span><mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>还是无济于事。

jackson的依赖包不缺,xml配置正常,ajax 也没有问题,controller也能正常访问,spring版本是3.2也不存在网上所说的版本冲突,这真是一个谜。

折腾了一个下午,终于找到了解决的方法:

@ResponseBody
@RequestMapping(value = "/information.jspx", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public String strategypost(HttpServletRequest request, HttpServletResponse response,
org.springframework.ui.Model modelMap,
@RequestParam(defaultValue="1")int pageNum,
@RequestParam(defaultValue="10")int pageSize) {
Site site = Context.getCurrentSite(request);
Map<String, Object> data = modelMap.asMap();
ForeContext.setData(data, request);

try {
Page<Information> page = informationService.findPage(pageNum,pageSize);
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> pageMap = new HashMap<String, Object>();
pageMap.put("page", page);
String json = mapper.writeValueAsString(pageMap);
return json;
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
$.ajax({
type:'POST',
url:'/information.jspx',
dataType:'json',
data:{'pageNum':pageIndex+1,'pageSize':${page.pageSize}},
success:function(data){
var result = data.page.result;
$.each(result, function (n, value) {
alert(value.title + ' ' + value.link);
});
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐