900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > spring MVC之返回JSON数据(Spring3.0 MVC+Jackson+AJAX)

spring MVC之返回JSON数据(Spring3.0 MVC+Jackson+AJAX)

时间:2019-09-10 16:23:53

相关推荐

spring MVC之返回JSON数据(Spring3.0 MVC+Jackson+AJAX)

参考:/blog/1985075

问题:在进行springmvc返回json数据的时候报如下错误:用上面的controller,访问:http://localhost:8080/demo/type.htm,报406错如下:

Failed to load resource: the server responded with a status of 406 (Not Acceptable) : The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

本文本的框架为:SpringMVC 3.2.3 \ jackson 1.9.2

传统的返回JSON格式的AJAX,用的方法一般是:在后台先把数据(Object)封装成JSON数据,再用HttpServletResponse返回。

本示例中,SpringMVC可直接支持JSON格式数据的返回。具体如下。

1、JAR包:SPRINGMVC包需的包,另外还需JACKSON的两个包。

jackson-core-asl-1.9.2.jar

jackson-mapper-asl-1.9.2.jar

2、spring-servlet.xml中加入:

Java代码 <!--返回JSON模版--> <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <propertyname="messageConverters"> <list> <beanclass="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>

我们在SPRING的配置中加入了一个新的适配器:AnnotationMethodHandlerAdapter,通过这个适配器,我们配置了一个属性,messageConverters,其中mappingJacksonHttpMessageConverter这个Bean,它就是用来处理json数据转换的。

注:我的项目中没有乱码现象,这样配即可,若有乱码现象,可以在MappingJacksonHttpMessageConverter的BEAN中配置supportedMediaTypes属性,是用于解决返回的乱码问题。

3、Controller中的使用

Java代码 @Controller publicclassSelectController{ @Resource privateTypeServicetypeService; @RequestMapping("/type") @ResponseBody publicObjecttype(){ List<Type>typelist=this.typeService.getTypeByParentid(Const.TYPE_DAILY); returntypelist; } }

在SpringMVC中可以在Controller的某个方法上加@ResponseBody注解,表示该方法的返回结果直接写入HTTP response body中。

------------------------------------------

遇到的问题:

用上面的controller,访问:http://localhost:8080/demo/type.htm,报406错如下:

Failed to load resource: the server responded with a status of 406 (Not Acceptable) : The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

查资料表明,不是JAR的版本问题,网友解答描述:

1、spring 3.2时requestedMediaTypes却为[text/html]的情况报406错误,还有一个原因可能是由于采用的后缀有关,如果使用*.htm,*.html等,默认就会采用[text/html]编码,若改成*.json,*.shtml等就OK

2、3.2.4 也遇到这个问题。修改ajax 请求的后缀为json 或者其他就可以了。他还是会优先根据url请求的后缀决定请求类型。所以你看到的一直是[text/html]

所以,将访问路径从http://localhost:8080/demo/type.htm改为http://localhost:8080/demo/type.json即可。

(如果你只拦截htm开头的链接,可以在web.xml里新增一个url-pattern为*.json的servlet即可。)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。