SpringMVC返回Json失敗,請檢查是否配置了Jackson
阿新 • • 發佈:2017-08-07
springmvc jackson json 配置文件
背景
需要一套幹凈的Spring+Spring MVC+Mybatis框架,框架寫到返回Json的環節報錯了。
問題
無法Json,報406
解決
需要配置Json工具包,這裏用Jackson
Maven Jackson
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.0</version> </dependency>
工程環境SpringMvc 4.x,不兼容Jackson2.9最新版。這裏特應用2.6版本
Spring Mvc配置
<!--Begin:使用Jackson 2.x的配置,需要導入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar--> <!--通過處理器映射DefaultAnnotationHandlerMapping來開啟支持@Controller註解--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <!--通過處理器適配器AnnotationMethodHandlerAdapter來開啟支持@RequestMapping註解--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <!-- 設置返回字符串編碼 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- json轉換器 --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!--End:使用Jackson 2.x的配置,需要導入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar-->
好了,重啟不報錯(一般就是jar寶沖突),[email protected]
以上配置,帶來好運,祝好 !
by.沫沫金
我得純凈框架,新模塊只需要一個Controller就可以,CRUD一句話全搞定。前臺專註Form就行。
本文出自 “沫沫金的IT心得與技巧” 博客,請務必保留此出處http://zl0828.blog.51cto.com/2242565/1954239
SpringMVC返回Json失敗,請檢查是否配置了Jackson